Skip to content

Lesson 4

Control Flow

while statement

Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly.

Repeated execution of a set of statements is called iteration. Because iteration is so common, Python provides several language features to make it easier. The first feature we are going to look at is the while statement.

Here is a function called countdown that demonstrates the use of the while statement:

def countdown(n):
    while n > 0:
        print(n)
        n = n-1
    print("Blastoff!")

You can almost read the while statement as if it were English. It means, While n is greater than 0, continue displaying the value of n and then reducing the value of n by 1. When you get to 0, display the word Blastoff!

More formally, here is the flow of execution for a while statement:

Evaluate the condition, yielding False or True. If the condition is false, exit the while statement and continue execution at the next statement. If the condition is true, execute each of the statements in the body and then go back to step 1. The body consists of all of the statements below the header with the same indentation.

This type of flow is called a loop because the third step loops back around to the top. Notice that if the condition is false the first time through the loop, the statements inside the loop are never executed.

The body of the loop should change the value of one or more variables so that eventually the condition becomes false and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop.

In the case of countdown, we can prove that the loop terminates because we know that the value of n is finite, and we can see that the value of n gets smaller each time through the loop, so eventually we have to get to 0. In other cases, it is not so easy to tell. Look at the following function, defined for all positive integers n:

def sequence(n):
    while n != 1:
        print(n)
        if n % 2 == 0:        # n is even
            n = n / 2
        else:                 # n is odd
            n = n * 3 + 1

The condition for this loop is n != 1, so the loop will continue until n is 1, which will make the condition false.

Each time through the loop, the program outputs the value of n and then checks whether it is even or odd. If it is even, the value of n is divided by 2. If it is odd, the value is replaced by n * 3 + 1. For example, if the starting value (the argument passed to sequence) is 3, the resulting sequence is 3, 10, 5, 16, 8, 4, 2, 1.

Since n sometimes increases and sometimes decreases, there is no obvious proof that n will ever reach 1, or that the program terminates. For some particular values of n, we can prove termination. For example, if the starting value is a power of two, then the value of n will be even each time through the loop until it reaches 1. The previous example ends with such a sequence, starting with 16.

break and continue statement

You can use break statement to break a loop. For example, the loop will break when x meets the condition: x + y == n.

def sum_n(n, y):
    x = 1
    while x <= n:
        if x+y == n:
            print(n)
            break

        x = x+1

With the continue statement we can stop the current iteration of the loop, and continue with the next:

x = 1
while x <= 100:
    if x % 3 == 1:
        continue
    x += 1
    print(x)

Example: Count the digits number

def num_digits(n):
    count = 0
    while n:
        count = count + 1
        n = n / 10
    return count

Example: Check whether a number is prime

def is_prime(n):
    x = 2
    while x != n:
        if n % x == 0:
            return False
        x += 1
    return True

Python Collections

There are four colletions data types in the Python programming language:

  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered and unindexed. No duplicate members.
  • Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.

list

Create lists:

A list is written written as a list of comma-separated values (items) between square brackets.

an_empty_list= []
another_empty_list = list()

a_normal_list = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
another_normal_list = [1, 2, 3, 4, 5, 6]

a_list_of_list = [ ["春", "夏", "秋", "冬"], ["Spring", "Summer", "Fall", "Winter"]]

Access items in lists:

You access the list items by referring to the index number:

Do remember that the first item has index 0.

>>> x = [0, 1, 2, 3, 4]
>>> print(x[0]) # The index of The first value of a list is 0.
0
>>> print(x[-1]) # The last value has index -1, and the second last value has index -2...
4
>>> print(x[4]) # The fifth value has index 4

Change values in lists:

Just like access the list items, you could use the index number and assignment operator to change an item in lists.

>>> my_favourite_color = ['black', 'red', 'yellow']
>>> my_favourite_color[1] = 'blue'
>>> print(my_favourite_color)
['black', 'blue', 'yellow']

Iterate a list

for x in list:
    print(x)
    # doSomething

We could use while statement too:

x = [0, 1, 2, 3, 4]
i = 0
while i < len(x):
    print(x[i])
    # doSomething
    # ...
    i = i + 1

Append an item:

>>> theia_students = ['Li Yuxi', 'Zhu Weicheng']
>>> theia_students.append('Lei Shile')
>>> theia_students.append('Wei Ziyi')
>>> print(theia_students)
['Li Yuxi', 'Zhu Weicheng', 'Lei Shile', 'Wei Ziyi']

Delete an item

>>> x = [1, 2, 3, 4]
>>> del(x[0])
>>> print(x)
[2, 3, 4]

tuple

A tuple is a collection which is ordered and unchangeable

Create a tuple

>>> t = (1, 2, 3)
>>> t1 = ('中文', 'English')
>>> fruits = ('Apple', 'Banana', 'Watermelon')

Access Tuple Items

Just like lists, you can use =[index]= to access tuple item

print(t[0])
print(t1[-1])

Check if Item Exists

Use in operator

>>> fruits = ('Apple', 'Banana', 'Watermelon')
>>> print( 'Apple' in fruits )
True
>>> print( 'Watermelon' in fruits )
False

set

A set is a collection which is unordered and unindexed. In Python, sets are written with curly brackets.

Create a Set:

thisset = {"apple", "banana", "cherry"}
print(thisset)

dictionary

Learn it by yourself.

Others

import statement

import statement which permits functions and variables defined in a Python script to be brought into the environment of another script or a running Python shell. For example, here is an example of a user-defined function that has a parameter:

def print_twice(param):
    print (param, param)

The interactive Python shell provides us with a convenient way to test our functions. We can use the =import= statement to bring the functions we have defined in a script into the interpreter session. To see how this works, assume the =print_twice= function is defined in a script named /lesson4.py/. We can now test it interactively by importing it into our Python shell session:

>>> from lesson4 import *
>>> print_twice('Spam')
Spam Spam
>>> print_twice(5)
5 5
>>> print_twice(3.14159)
3.14159 3.14159

How to Install Libraries

There are several methods to install libraries. I recommend =pip= tool which is almost 'built-in' and very convenient to use.

Assume that you need installing a library about image processing which named =Pillow=, so you could use the command below in a terminal:

  • MacOS

    pip3 install Pillow
    
  • Windows

    pip install Pillow
    

Now we could test the installed libraries in an interactive shell:

>>> from PIL import Image, ImageFilter
>>> im = Image.open('test.jpg')
>>> im.show()
>>> im2 = im.filter(ImageFilter.FIND_EDGES)
>>> im2.show()
>>> from PIL import Image, ImageFilter
>>> im3 = im.filter(ImageFilter.BLUR)
>>> im3.show()
>>> im4 = im.filter(ImageFilter.SHARPEN)
>>> im4.show()
>>> im4.save('new.jpg')

Excercise

  1. Write a function sum_of_squares_of_digits that computes the sum of the squares of the digits of an integer passed to it. For example, sum_of_squares_of_digits(987) should return 194, since \(9^2 + 8^2 + 7^2 == 81 + 64 + 49 == 194\).

  2. Write a function print_primes that find all prime numbers which is less than the given integer passed to it. You should implemented the function is_prime.

  3. Write your own version "guessing number game". The example of generating a random int number are given below:

import random
# generate a random integer betwen 10 and 100(not include)
random_number = random.randint(10, 100)

Homework

Install jupyter notebook and download the exersice book here exercise2.ipynb to finish ten excersice.

  • MacOS

    pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple jupyter
    
  • Windows

    pip install -i https://pypi.tuna.tsinghua.edu.cn/simple jupyter
    

Next you could run the command jupyter, and a browser window will open. Navigate the directories of your system and find your downloaded notebook excersice2.ipynb and open it, now you can finish your excersice in that notebook.

Note: You need to learn dictionary by yourself, and here are some URLs you could explore.