The Basics: Getting Started Quickly

When you install Python 3 on your computer, you also get a very simple yet usable IDE called IDLE, this is all you need when to start out. You may also use PyCharm Educational Edition, it's a free editor which you can use for writing Python programs.

From now on, we will assume that you have Python installed on your system.

We will write our first Python program. Once you have started Python, you should see >>> where you can start typing stuff. This is called the Python interpreter prompt.

The Python Shell, is used to run snippets of Python code, usually a single statement. At a time, we will start from here >>>

1.1 Every body say Hello (print something)

At the interpreter prompt type the following and [enter] key:

>>> print ('Hello, Buzz Coders!')
'Hello, Buzz Coders!'

The first line after >>> is your typing, the second line is what you will see printed on the screen. print( )command means 'show on the screen", not 'send to the printer'.

What's wrong here:

>>>print Hello
>>>print 'Hello'
>>>Print ('Hello')

Just keep in mind for now: print( ) is a function, the parenthesis is required. Here it's color is blue text, means it's command. The text in the parenthesis is green to show that it's data.

When you print different data types in one line, such as some strings and numbers, you can use comma ',' to separate them. We will get to `data types' soon.

>>>print('Hi ', 3 , 'little bears!')

Comments

When we write programs, we often need to add notes for other readers of the program or maybe yourself 6 months later. So add comments for explanation and reminders.

'#' sign is for comments Comments in Python start with the hash character, #, and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal.

Text at the right of this # is ignored by Pytnon. The color is light gray. Check the following example:

>>>print ("This will run.")  # This won't run.
This will run.
>>>print ("I can put a '#' sign here.")
I can put a '#' sign here. 
        # The '#' sign above is part of a string.
>>>
 # NumberGuessingGame.py
 # This is a game, the computer will generate 
 # a random number from 1-10, if the number the player
 # input from keyboard is the same, the player wins.

1.2 Basic Data Types and Values

Let's meet the first two basic data types in Python:

  • 8 is an integer
  • 8.5 is a floating point number
  • "Hello" is a string

They are values - one of the fundamental things - that a program manipulates.

If you are not sure what data type (class) a value falls into, Python has a function called type() can tell you.

>>>type(2)
<class 'int'>    # integers belong to the class 'int'
>>>type("Hi, there!")
<class 'str'>    # strings belong to the class 'str'

New vocabulary:

  • Python refer to these values like integer or string as objects.

  • These objects are classified into different classes, or data types. In later chapters, we will see how to create our own types using classes.

It's OK if you don't understand them now, just keep in mind for later.

1.3 String

A string is a sequence of characters include letters, numbers, punctuation, plus hundreds of other special symbols.

You can specify strings using:

  • Single quotes, such as 'Hi', '1208N'
  • Double quotes, such as "Hi", "His cat"
  • Triple quotes, you can specify multi-line strings.

You might guessed, using single and double quotes enable us to conveniently handle " and ' characters inside strings:

"It's my cat."
'He said "Yes!"'

Using triple quotes (""" or '''), you can use single quotes and double quotes freely within the triple quotes. An example is:

'''This is a multi-line string. This is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bean, others call me 'Mr. Bean'!"
'''

You can add two string together to be a longer string

>>>print('Hello, ' + 'how are you?')
Hello, how are you?

Escape Sequence \

Another way for you to use quotes in a string, use the backslash \ as escape sequence, then the quote character is treated as part of the string, so Python won’t be confused as to where the string starts and ends.

>>> print ('These are Sally\'s books.')
These are Sally's books
  # The single quote ' after \ will not be treated as the end of the string

some useful escape charactors

\' single quote \" double quote \\ backslash \n newline (line feed) \r return (carriage return) \t tab (horizontal tab)

1.4 Numbers and Simple Math

Numbers are mainly of two types:

  • Integers are whole numbers: 2, 8, 1000 are integers.

  • Floats are floating point numbers : 8.0, 3.23 and 52.3E-4. The E notation indicates powers of 10.

Basic Operators:

We will briefly take a look at the operators and their usage.

  • addition +
  • subtraction -
  • multiplication*
  • power **
  • division /
  • floor division(integer division) //, divide and round the answer down to the nearest whole number

  • modulo %, returns the remainder of the division

  • Absolute value abs()

Notes:

1. Python arithmetic follows the same evaluation rules as regular arithmetic. 2. Parentheses () can be used for grouping 3. There is full support for floating point; If there is a float in a mixed type operation, integers would be converted to floating point. 4. Division always returns a floating point number as in Python 3.6.0

Example to practice:

>>> 7.0 / 2   # see Note 3 or 4
3.5
>>> 3 * 3.75 / 1.5
7.5
>>> 13/3
4
>>> -13/3     # nearest whole number
-5
>>> 13% 3
1
>>> abs(-10)
10
>>> (3+5)*2**3       
64
>>> (3+4)*(5**2-5)         140

More practice:

>>>print ("I will count my stuff, pencils: ")
I will count my stuff, pencils:
>>>print (20 - 3)
17
>>>print ("ball pen: ", 5 + 2 )
ball pen: 7
>>>print ("I have many books: ", 5*8, "total.")
I have my books: 40, total.
>>>print ("I have wiggly worms: ", (30+10)/5 )
I have wiggly worms: 8

Note:

  • 'Increment by' operator +=, and others

    x += 2 means x = x+2, for less typing. x-=1 same as x = x -1 x*=3 is what? (x = x *3)

More on type Converting between types: integer, float, string


>>> float (8)    # convert an integer to a float
8.0
>>>float ('9')    #convert a string to a float
9.0

>>>   # float to integer

>>> int(5.18)        # int() chops off extra digits
5
>>> round(8.65)      # round() does the usual rounding off
9
>>> round(8.5)
8
>>>1/float(2)     
0.5
>>> str(-9.18)
'-9.18'
>>> str(58)       # convert integer 58 into a string
'58'
>>>print('Add them: '+str(5)+' plus'+str(10)
          + ' is', 5+10)               
Add them: 5 plus 10 is 15
# string + string valid
>>>
>>> int ('5')    # '5' is a string here
5                #  now 5 is an integer

Actually, the int() is a class but all you need to know right now is that you can use it to convert a string to an integer, if:

  • assuming the string contains a valid integer like 3, 5, 20 in the text.
  • You will get a ValueError if you try to convert a string that doesn't contain a number in digits:
    >>>age='ten'
    >>>number_age=int(age)
    ...
    ValueError: invalid literal for int() with base 10:'ten'
    

    1.5 Variables and Values

Simply put, a variable is a name that refers to a value. Assignment statements create new variables and also give them values to point to.

message = "What's up, Doc?"  # A string value
n = 17                       # An integer
pi = 3.14159                 # A float

This example makes three assignments. The first assigns the string value "What's up, Doc?" to a new variable named message. The second gives the integer 17 to n, and the third assigns the floating-point number 3.14159 to a variable called pi.

  • The assignment token, =, should not be confused with equality (we will see later that equality uses the == token).
  • Assign value to a variable: variable name = value
  • The type of a variable is the type of the object it currently refers to. You can assign a value to a variable, and later assign a different value to the same variable.

Variable Name: (identifier)

Variables are examples of identifiers. Identifiers are names given to identify something. There are some rules you have to follow for naming identifiers:

  • They can contain both letters, digits(0-9) and underscore _**, but they have to begin with a letter or an underscore.
  • Case sensitive
  • No Keywords. Keywords define the language’s syntax rules and structure, and they cannot be used as variable names. Python has thirty-something keywords: and as assert break class continue def del elif else except exec finally for from global if import in is lambda nonlocal not or pass raise return try while with yield True False None

Examples of valid identifier names:

my_name
price_of_tea_in_england
i 
_2_3

Invalid identifier names

2things = "big parade"
more$ = 1000000
class = "Computer Science 101"
this is spaced out 
my-name 
>a1b2_c3.

If a variable is not “defined” (assigned a value), trying to use it will give you an error:

>>> n        # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

Variables' values can change We use variables in a program to “remember” things, like the current score at the football game. But variables are variable. This means they can change over time.

Check to see the following lines you will get the idea:

>>> x = 'Monday'   # Assign string 'Monday' to x
>>> print ( x )
Monday             # x value is 'Monday'
>>> x ='Friday'    # Assign 'Friday' to x
>>> print ( x )
Friday           # x value changed to be 'Friday'
>>> x = 8        # Assign different type integer 8 to x
>>> print x 
8                # x get value integer 8

sequence of assignments:

>>>x=8
>>>x
8
>>>y = 'cat'
>>>y
cat
>>>x = y            # assign the value of y to x
>>>x
cat

Multiple Assignment

>>> x, y, z = 8, 'two', 3.5
>>> x
8
>>> y 
two
>>> z
3.5
>>> x, y, z
(8, 'two', 3.5)    # tuple? (value1, value2, value3)

exercise

Check your understanding

>>> x=2              # assign 2 to variable x
>>> y=3
>>> print ('x+y=', x+y, ',x*y=', x*y)
x+y= 5, x*y= 6
>>>
>>> a=3
>>> b=a
>>> a=5
>>> print a, b
5,3
>>>
>>> x = 12
>>> x = x - 1   # same as x -= 1
>>> print(x)
11

More exercise to work with: Ex. 1.5-1 fruit.py

fruit_total=30
bananas=12
apples=fruit_total - bananas

apples_sold=5
bananas_sold=2

apples_left=apples - apples_sold
bananas_left=bananas-bananas_sold
fruit_in_stock=apples_left+bananas_left

print ("fruit in stock:",  fruit_in_stock)
print ("Apples left: ", apples_left, 
       "and bananas left: ", bananas_left)

Ex. 1.5-2 restreuant_bill.py

>>>bill = 56.24
>>>tax_R = 11%
>>>tip = 18%
>>>tax = bill* tax_R
>>>bill += tax
>>>total_payment = bill + bill*tip
>>>print ('Your total payment is: ', total_payment)

Ex. 1.5-3 reverse_number.py Please reverse 45 to be 54, here 45 is an integer.

>>>
>>> n=45
>>> a=int(n/10)     # now a is 4
>>> b=n-a*10        # now b is 5
>>> print (b*10 + a)
54

If you treat 45 as a string, there is another way to reverse it easily using string indexing, see Chapter 2, Ex. 2-

1.6 Reading strings from the keyboard, the input( ) function

To print out something on the screen we can use print()function, while if we want to get some information from the keyboard (the user), we can use input() function to get strings from user. Look at this:

>>> name = input('Please enter your name here: ')
Please enter your name here: Sounders
>>> print ('Hello, ' + name + '!')
Hello, Sounders!

The first line calls the input( ) function, when it runs, the prompt message 'Please enter your name here: ' appears in the output window, followed by a blinking cursor, waiting until the user enters a string and presses [Enter]. So the variable name gets the string value that the user types in.

The input() function takes a string as argument and displays it to the user as prompt message. Then it waits for the user to type something and press the return key. the input() function will then return the text the user has entered as a string value.

Example:

>>>string_num = input('Enter a digit number: ')
4
>>>integer_num = int(string_num)
>>>print(string_num +10)
Traceback (most recent call last):
  File "<input>", line 4, in <module>
TypeError: Can't convert 'int' object to str implicitly
   # str value and int value can not use '+' operator
>>>print(integer_num + 10)
14      # integer_num is a integer, can do '+10" 
>>>

In the above example, we get a number as a string from input()and assign it to string_num , then using int() to convert it into a integer, and store it in the variable integer_num. For the first two lines we can achieve the same result using:

>>>integer_num = int(input('Enter a digit number: '))
# get a number as string from input() and convert it 
# into integer right away, then assign it to integer_num

The input() function only returns strings. Another example: Ex. 1.6-1 name_age.py

# name_age.py
name = input('Enter name: ')
age = input('Enter age: ')
age5 = int(age) + 5
print(name.capitilaze() + ' will be ' + age5 + 'in 5 years.')
... 
...# run the file and the results:

Enter name: sounders
Enter age: 10
Sounders will be 15 in 5 years.

In the program, the second line the input() function returns a string '10' and assign it to variable age. We need to use type conversion function, int(s), to convert string to a integer. We can also type in:

age = int(input('Enter age: '))
age5= age + 5

results matching ""

    No results matching ""