Basic: Run Python (90 minutes)

Expressions

Expressions are literal values or variables combined with operators such a s +, -, * and /, also, parentheses () can be used for grouping.

Types

The very basic types in Python are numbers and strings. Numbers could be integers, floats and complex numbers. Strings could be normal (ascii) strings and Unicode strings.

The equal sign (=) is used to assign a value to a variable. Variables should be used after initialized, otherwise you will get an error.

# integers
answer= 42
negOne = -1

#floats
weight = 129.3

# strings
msg = "Hello"
helloInChinese = u'你好'

There are different ways to initialize a string, ' ... ' (single quote), " ... " (double quote), and """ ... """ or ''' ... ''' (triple quote).

There’s no difference between single quote and double quote, if you need a real double quote character (') in your string, you can use a double quoted string.

msg = "Hi, I'm Jack."
msg = 'This is "magic" !'

Triple quoted strings are used to represent multiple-lined strings.

"""
TWO roads diverged in a yellow wood,
And sorry I could not travel both
And be one traveler, long I stood
And looked down one as far as I could
To where it bent in the undergrowth
"""

Operators

Let’s play some operators with numbers. Note, Python will convert from integer to floats implicitly when you try to make a binary operator work on an integer and a float. Addition to + - * /, we have % for modulo, ** for power.

2 + 2
50 - 5*6
(50 - 5.0*6) / 4
8 / 5.0
17 / 3     # int / int -> int
17 / 3.0   # int / float -> float
17 % 3     # the % operator returns the remainder of the division
5 * 3 + 2  # result * divisor + remainder
5 ** 2     # 5 squared
2 ** 7     # 2 to the power of 7

Now we can replace literal values with variables.

width = 20
height = 5 * 9
width * height
# 900

Common strings-operators are * (repetition), + (concatenation) and [] (subscription). You must use * with an integer and a string, use + with both sides string. The first character has index 0. Python is different from other languages, there’s no “character type”, a single character is just a string in size one.

>>> 'a' * 10
'aaaaaaaaaa'

>>> name = 'Jack'
>>> 'Hello, ' + name + '!'
'Hello, Jack!'

Python supports slicing (substring) operation: [a:b] or [a:b:c] means the substring starts from position a, stops at position b, step by c. The default value of a is 0, b is the end of the original string.

# this is a very long word
>>> word = 'Pneumonoultramicroscopicsilicovolcanoconiosis'
>>> word[0]
'P'
>>> word[3]
'u'
>>> word[-1]
's'
>>> word[-0]
'P'
>>> word[-10]
'n'
>>> word[5:]
'onoultramicroscopicsilicovolcanoconiosis'
>>> word[:5]
'Pneum'
>>> word[::3]
'Punlacspsivcons'
>>> word[::-1]
'sisoinoconaclovociliscipocsorcimartluonomuenP'

You can use len() to get the length of a string.

>>> len(word)
45

You can read Built-in Types in Python doc for more about types and operators.

Data containers

You can have a lot of separated variables in your Python program, but it’s a good idea to group them together.

Data containers are containers for variables and values, you can them like a set or a collection of some variables/values.

tuple

Tuples are used to represent an immutable, ordered set of stuffs, elements inside tuples are separated by commas.

Although parentheses are not always necessary, still, you should put them them you want to tell other people you’re using a tuple here.

# an empty tuple
>>> ()
()
>>> t = (12345, 54321, 'hello!')
>>> t
(12345, 54321, 'hello!')

Tuples are immutable, but you can put mutable elements (such as variables) inside a tuple. For example, this is a very common idiom for variable swapping.

>>> a = 55
>>> b = 66
>>> (a, b)
(55, 66)
>>> (a, b) = (b, a)
>>> (a, b)
(66, 55)

list

Lists are used to represent an immutable, ordered set of stuffs, elements inside lists are separated by commas.

# an empty list
>>> []
[]
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

Like strings, you can use subscriptions and slicing on lists.

>>> squares[0]    # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:]  # slicing returns a new list
[9, 16, 25]

Lists are mutable, you can change the elements inside a list.

>>> cubes = [1, 8, 27, 65, 125]
>>> cubes[3] = 64
>>> cubes
[1, 8, 27, 64, 125]

Strings, tuples, and lists are all sequential types, we can perform same operations on them!

concatenation, repetition, subscription, slicing, length ...

>>> cubes = [1, 8, 27, 64, 125]
>>> squares = [1, 4, 9, 16, 25]
>>> squares + cubes
[1, 4, 9, 16, 25, 1, 8, 27, 64, 125]

>>> squares * 3
[1, 4, 9, 16, 25, 1, 4, 9, 16, 25, 1, 4, 9, 16, 25]
>>> squares * 3 + cubes * 2
[1, 4, 9, 16, 25, 1, 4, 9, 16, 25, 1, 4, 9, 16, 25, 1, 8, 27, 64, 125, 1, 8, 27, 64, 125]

>>> (squares * 3 + cubes * 2)[::5]
[1, 1, 1, 1, 1]
>>> len((squares * 3 + cubes * 2)[::5])
5

dict

A dictionary is an unordered set of key-value pairs, keys are unique (within one dictionary).

>>> scores = {'Jack':95, 'Tom' : 86, 'Emily': 99}
>>> scores['Jack']
95
>>> scores.keys()
['Emily', 'Jack', 'Tom']

>>> del scores['Tom']
>>> scores.keys()
['Emily', 'Jack']

Control flows and basic algorithms

Now it’s time to learn more about controlling the behavior of our program. The basic concept of control flow is: sequential execution and conditional jump.

  1. By default, your program will run one line by another.
  2. When there’s a conditional jump, we move to another part of the program and start from there.

Conditions and loops

if-else blocks

Consider the usage of if in English language.

If I study, I will pass the exam.

If the predicate is true, then something is going to happen.

In Python programming language, a if statement means that if a “conditional expression” returns True, then execute the following block. elif (read: else if) and else blocks are optional, you can add them if you need.

answer = 42
if answer == 42:
    print("the answer to life, the universe and everything!")
else:
    print("wrong answer, sorry.")

print("End of a if-else block")

In the above example, answer is an integer (42), we compare it to 42, that is obviously True. The python interpreter will execute the inner block.

Note that in Python programming language, indentions do matter! We recommend you to use 4 spaces for an indent level. Python doesn’t like other languages, blocks are represented by different levels of indents.

A predicate could be a comparison, or a certain condition, which returns Ture or False. You can combine several predicates with and/or/not operators.

<   less than
<=  less than or equal
>   greater than
>=  greater than or equal
==  equal
!=  not equal

Ex.
a > b
a == b
value in [1, 2, 3]

See: Truth Value Testing

while blocks

Computers help people to do boring jobs, especially repetitions. Another control structure in the Python programming language is while loop.

while loops are quite easy to understand, for a given if block, repeat the jobs inside the block while the predicate returns True.

  • This will print only one line.

    i = 0
    if i < 10:
        print(i)
    
  • This will print ten lines, from 0 to 9.

    i = 0
    while i < 10:
        print(i)
        i = i + 1
    

While we arrive the end of the block, we jump back to the very beginning of the while block and test the predicate. If it returns True, execute the block, otherwise, jump out of the loop.

We call the structure above “loop”. The program will loop the inner block (usually called “loop body”) again and again for given condition.

Take a look at variable i, inside the inner loop, you must make some changes to the variables in the predicate, otherwise the loop will never end.

  • A “infinity” loop

    while True:
        print("The Galaxy Express 999")
        print("will take you on a journey")
        print("a never ending journey")
        print("a journey to the stars")
    

for blocks

In most of the cases of loops, we have a counter i or j to record the times of the loop. Python offers another syntax for this kind of use: for loops.

for i in range(10):
    print(i)

In python 2 (different from python3), range() yields a list.

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 10, 2)
[1, 3, 5, 7, 9]

for i in range() is a syntax sugar for this kind of loops, python will put each element from the list inside i, you can use i inside the loop body.

The concept of this kind of behaviors is called “iteration”, we get an element one by one from a sequential type.

Similarly, we can iterate over a string or a list/tuple.

>>> for c in "Hello":
...     print(c)
H
e
l
l
o

>>> for e in [1, 2, 3, "gg", 55.66]:
...     print(e)
1
2
3
gg
55.66

>>> for e in (5566, "never", "die"):
...     print(e)
5566
never
die

Sometimes you might need both the element and the index points to that element, enumerate will return a tuple of the index and the element at the same time.

>>> for i, x in enumerate("hello"):
...     print(i, x)
(0, 'h')
(1, 'e')
(2, 'l')
(3, 'l')
(4, 'o')

Functions and methods

Functions

It’s a good idea to cut different parts of your code to little independent blocks, that is called encapsulation. We make our programs to little tiny components and combine them to a big whole castle.

def hello():
    print("Hello")

hello()

We define a function called hello, it prints hello. When we want to “call” the function, we use a pair of parentheses right after the name of the function.

Functions can take arguments (sometimes we call them parameters), you “pass” arguments to a function and it will do some stuffs.

>>> def say(s):
...     """
...     print the string s
...     """
...     print(s)
>>> say("hi")
hi
>>> say("Hello")
Hello
>>> say("Morning")
Morning

Also, it’s a good habit to write down the description via a docstring in the very beginning of a function. You can use help() to read the document of the function.

>>> help(say)
Help on function say in module __main__:

say(s)
    print the string s

Also, you can write down your functions in a file and import it from other programs.

  • bar.py

    def f():
        print("in bar.py, function f()")
    
  • foo.py

    import bar
    
    bar.f()
    

Computer science is a study of abstraction, programmers encapsulate the details of implementation inside functions, you don’t need to understand the details of a function but read the documentation and use it.

Methods

Methods are like functions but belong to objects/classes.

Python is an object oriented programming language, the language already provides lots of builtin types and methods. You can use help() and dir() to figure them out.

  • for instance, we want to uppercase a string, try to find if that is a builtin method of type str.
>>> help(str)

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Awesome, it looks like that we can use str.upper, it takes a string (instant) and returns a copy of uppercased string.

| upper(...)
|     S.upper() -> string
|
|     Return a copy of the string S converted to uppercase.
>>> "wow! It's the power of python!".upper()
"WOW! IT'S THE POWER OF PYTHON!"

Note: Always try to use builtin types/methods before you create your own. You can google for the jobs you want to do or read the python online documentation.

For example, you want to capitalize a string in Python, the query of googling might be:

Google: python capitalize a string

https://stackoverflow.com/questions/352478/capitalize-a-string
https://docs.python.org/2/library/string.html

Reading the python documentations and the answers on stackoverflow helps you discover more!

See: The Python Standard library

User defined data structures

Sometimes builtin types are not enought for our tasks. We can define our types in Python.

class MyCar(object):
    def __init__(self, speed, color):
        self.speed = speed
        self.color = color

    def go(self):
        print("Hi, I'm a " + self.color + " car, I can run at " + str(self.speed) + "Km/h!")


car = MyCar(100, "red")
car.go()

Note the first argument of these methods, it refers to the class instant itself. The “initialization” of an instance should be a class method called __init__, it will be involved when an instance is created.

Instance variables are defined as self.xxx, you can store some information for an instance.