[PyTUT 6] CONTROL STRUCTURES

Hi everyone!

First of all, I would like to say thank you to all my friends and people who support me to make this series of Python tutorial. Two weeks ago, I shared the series with some of my friends and got many positive comments from them and they encouraged me to continue further. I would say that your concern really is my motivation to continue to do this.

OK now, let’s take a look at last tutorials a bit, in which, I introduced how to do some basic math with numbers, play with strings and three types of Python array, then assign values to variables.

To take a further step, in this tutorial, I want to show you control structures in Python.

By the way, I set up a new account on Github and from now, all codes will be published to the link below.

https://github.com/tenga061/basic_python_tutorials

And all codes in this tutorials were published on:

https://github.com/tenga061/basic_python_tutorials/tree/master/pytut6_control_structure

As usual, I recommend you to read the following topics before beginning this tutorial.

Introduction

There are three types of control structures as you can see in Fig. 1. The first one is sequence structure that you used in the preceding tutorials. The second and last one is selection and loop structure, respectively.

Fig. 1. Flow charts of three types of control structures [1]

In most programs, the two last structures proved to be helpful to make the codes more concise or more clear. But now, before beginning with them, let’s try using sequence structure again to make a simple program that print numbers from 0 to 9 on the screen but using Python script editor instead of Python Shell (or Python interpreter prompt).

Sequence

To open Python script editing window, do the following steps:

• First, you need to open IDLE (read [PyTUT 1] AN INTRODUCTION OF PYTHON again if you don’t remember how to open IDLE).
• Second, press CTRL + N  or left click on File -> New File on IDLE tool bar in order to open the Python script window.

Fig. 2 Open IDLE script
• Third, in Python script editing window, press CTRL + S or left click on File -> Save and name the file to save the script. Actually, it is unnecessary to save the script when you begin to code, but you ultimately must do this if you want to run the script.

Fig. 3 Save script file

Following to this, we will start to write a first script that print the numbers from 0 to 9.

print 'The number from 0 to 9'
print 0
print 1
print 2
print 3
print 4
print 5
print 6
print 7
print 8
print 9

After that, press F5, then select OK when you are asked whether you wanna save this program or not in order to run the script (see Fig. 4).

Fig. 4 Save all changes in your code before running

The result is showed in Fig. 5.

Fig. 5 The result was showed on Python Shell

As you can see, in sequence structure, the computer will start to run the program from the begin to the end and follow the statements in order. However, imagine what if you want to print the numbers from 0 to 10,000. OK, it is still possible if you have a lot of time, right? Believe me, you will not want to do this.

For the reason of this, in the next section, I will introduce to you repetition structures which will help you to solve such repetitive problems.

Repetition

As I mentioned before, repetition structures are useful for repetitive problems. There are three types of repetition structures, including: for-loop, while-loop, and do-while-loop. First, look at the for-looping structure as showed in Fig. 6.

For-Looping Structure

The flow chart in Fig. 6 was taken from a C++ book but I think it’s still good to help you understand the mechanism of the for-looping structure in Python or even in any other programming languagues you want to learn in the future.

Fig. 6 For-Looping Structure [1]

In C++, to create a for-loop, you first need a initial statement to initialize a loop variable. Then, declare a loop condition such as i < 10, where i is a loop variable. If i satisfies the condition (i < 10), statements in the loop will be performed and the loop variable will be updated after that (like i = i + 1 or i = i + 3, etc.). By contrast, the computer will close the loop and perform another statement.

The mechanism of for-loop in Python is similar to C++. However, if you were not familiar with C++ before, it still is OK. Let’s take a look at the example below that print numbers from 0 to 10 using the for-looping structure in Python:

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

As you can see, to create a for-loop in Python, we first initialize a loop variable i, just like C++. However, there is a little bit different from C++. In Python, to create a loop condition, we use range(m, n) function which make a list from m to (n-1) with n>m, the upper bound n of the range function is implied as the loop condition i < (n-1). Additionally, the loop variable will automatically update itself in every value in the list in every loop (see Fig. 7 to understand how it works).

Fig. 7 The way the for-loop structure work in Python

Now, what if you want to print only odd numbers from 0 to 9? Fortunately, you can add step argument into the range(m, n, step) function. So, the code become:

for i in range(1, 10, 2):
print i

(This script is available on: https://github.com/tenga061/basic_python_tutorials/blob/master/pytut6_control_structure/lab2_for_loop.py)

The results are illustrated in Fig. 8.

Fig. 8 For-looping structure example results

Not only those, for-looping structure of Python is even more flexible, by which, you can loop to print arbitrary numbers as you want by assigning the value of each element in the list to loop variable.

arbitrary_numbers = [9, 123, 59, 1039, 23, 27]
for number in arbitrary_numbers:
print number

You can even do this for tupe:

lovely_cities = ('Paris', 'Los Angeles', 'Seoul', 'Tokyo')
print 'Here is some of the lovely cities: '
for city in lovely_cities:
print '   + ' + city

Or dictionary type:

hp_characters = {'Danial Radcliffe': 'Harry Potter',
'Emma Watson': 'Hermione Granger',
'Rupert Grint': 'Ron Weasley'}
for actor, character in hp_characters.iteritems():
print actor + ' played ' + character + ' in the series of Harry Potter'

OK, you saw how useful is it when using for-loop to solve repetitive tasks. But you can only use the for-loop if you know exactly how many time it loop. For some problems that you don’t now the number of loop, you need to use while-looping structures which will be introduced in the next section.

While-Looping Structure

Fig. 9 While Looping Structure [1]

As I mentioned before, in while-loop, you don’t needa know how many times your loop will run but loop conditions such as $i \leq n$ or $i \neq n$. In the case, we use while-looping structure.

While-looping structure begin by checking the condition loop or expression like $i \leq n$. Then, if the condition is satisfied, statements in the loop will be executed. Otherwise, the loop will be ended. Note that, of course we can’t type symbol like $\geq$ or $\neq$ in any programming languages. Instead, we use these signs in the table below.

Table 1. Relational operators [1]

For example, we want to write a program that read arbitrary numbers from user. If the number is equal or less than 9, the program is continue, by contrary, it stop and print the line “Goodbye and see ya”.

user = 1

while (user<=9):
a = raw_input('Please enter an arbitrary number: ')
user = float(a)

print 'Goodbye and see ya'

Now, what if you wanna use more than one looping condition, for example, the program will continue requiring you to enter an arbitrary number if your entered-number is equal or less than 9 and more than 6. In the case, we needa use boolean operator and.

user = 1

while (user>6) and (user<=9):
a = raw_input('Please enter an arbitrary number: ')
user = float(a)

print 'Goodbye and see ya'

Similarly, you can use boolean operator or in Python by typing or. It’s little bit different for people who were familiar with C++ or other lower programming language, in which, they must use && for the boolean and and || for the or. So, please note that, in Python, we just needa type and for the and and or for the or.

Do-While-Looping Structure

Fig. 10 Do-While-Looping Structure [1]

The only difference between while-loop and do-while loop is that statments in the loop will be excuted at least one. In detail, if the looping condition is wrong from the begining of the loop, the while-loop will end without any statements executed, while statements in do-while-loop still is executed once because it is executed before looping conditions are checked.

Nested Looping Control Structures

Just like other programming languages, we can use looping structures in looping structures to handle more complicated tasks. You can write a simple code that paint a Christmas tree using only for loop. Here is my sample:

for m in range(3):
for i in range(1, 5+m):
for j in range(5-i+1):
print ' ',
for k in range(5-i+1, 5+i):
print '*',
print

And the result:

Python loop controls

In this part, I would like to introduce some special commands that help you handle your loop somtimes.

pass

As its name, it mean ‘don’t do anything’. It sounds pointless, but sometimes we use it with the loop to wait for an occurrence of an event or an interupt.

Here is an example of using pass command in a loop:

while(1):
pass

The program above will run until you close the termial.

break

This command is another way to end looping structures whenever it satisfy the condition that you set.

For example,

i = 0
while 1:
print i
i = i + 1
if i > 5:
break

Running the program and you will get the result as illustrated in Fig. 12.

Theoretically, the program should run and print the value of i till we close the terminal. However, because we set a break in the if block (will be introduced in the next section), the break break the loop when i = 6.

Fig. 12 An example of using break for while-loop

You can also use the break command in for-loop. The example below using for-loop but show the same result.

for i in range(10):
if i > 5:
break
print i

When I was an undergraduate student, my professor who taught me the subject ‘Programming Fundamentals’ often prohibit us from using this command because, as he said, the break break the structure of programs. However, I think this control command sometimes is useful, especially, it is used frequently in programming for microcontroller. Anyway, you should consider carefully if you want to use it in your program.

continue

This command returns the control to the beginning of the loop. Let’s run the following program to see how it work.

i = 0
while i<10:
i = i + 1
if i == 5:
continue
print i


The result is described in Fig. 13.

Fig. 13 An example of using the command continue in a program

We can see that the command continue in the program above is the reason why we miss the number 5. In details, when i reach the value 5, the if condition is satisfied, then the command continue is run. As a result, the control of the loop go back to the begining without execute the line print i (i.e print i = 5 on the screen).

Selection

Now, we turn to the last structure of this tutorial – selection or if-structure. In the previous section (Python loop control), I briefly show you using the selection structure to make condition for breaking the loop. Now, we introduce further.

One-Way Selection

The simplest form of selection structures are one-way selection. In which, we use an if condition or expression to decide whether statements should be executed or not. In selection structures, the expression is described as the same way as the expression of while-loop in Table 1.

Fig. 14 One-Way selection [1]

Let’s me show you an example in the normal life. Assume that you go to the market and want to buy a fish for lunch. You go to a stall and ask the price of a fish, if it is lower than $10, you buy it, but if not, you don’t. Here is a code: print 'How much money for this fish?' fish_price = raw_input("It's:$")
fish_price = float(fish_price)
if fish_price>10:
print 'Sorry, I don\'t wanna buy it'

Now, run the program, enter 20 for the cost of the fish, you will get the result ‘Sorry, I don’t wanna buy it’.

Multiple Selection

Fig. 15 Two-Way selection [1]

From the view of real life problems, you can see that it’s not simple like that. Here is another script: You go to the supermarket, ask the price of the fish, if the price less than $10 then you buy it, if not, you deal with the salesman that if you could buy it with the price of$13.

To do the script above we need to know how to use the multiple selection structure. Here is the structure of two-way selection (as described as Fig. 15)

if condition:
statements
else:
statments_2

If you need more than 2, we use elif for conditions and else for the last one.

if condition_1:
statements
elif condition_2:
statements_2
...
elif condition_n:
statments_n
else:
statements_(n+1)

Here is the script of the problem above.

print 'How much money for this fish?'
fish_price = raw_input("It's: $") fish_price = float(fish_price) if fish_price<10: print 'OK, give me one.' else: print 'Could I buy it with$13?'

Nested Selecting Control Structures

Just like repetition structures, you can put selection structures into others. Here is a small example of using nested selecting control structures.

Just for fun

OK, so, I introduced you the foundation of control structures in Python. Now we can use it to make a simple entering-password code. In which, users are asked to enter their password, if the entered password is right, the program will show them where were  the mythical treasures hide, if not, the program will end with curse: ‘You have wrong answer for 5 times. Now, you will not be able to eat candy. Ha ha ha!’.

So this is the end of this topic. In the next, I would introduce you function, class and package in Python. Goodbye and see you again.

Hope you enjoy it,

Curious Chick

References

[1] D. S. Malik, C++ Programming: From problem analysis to program design (Sixth Edition), Cengage Learning (2013)