4. Flow Control#

4.1. Conditional statements#

It is very common for a program to have sets of instructions that are executed conditionally. To achieve this behaviour python has if, elif, else blocks. The general syntax for these conditional blocks is

Syntax:

if <condition>:
    <code block>
elif <condition>:
    <code block>
elif <condition>:
    <code block>
else:
    <code block>

Where:

  • <condition>: a statement that can be evaluated as true or false.

  • <code block>: valid python code.

  • The clauses elif and else are optional and several elifs may be used, but only a single else can be used and must e at the end.

4.1.1. Example 1#

temp = 23 # temperature value used to test

if temp < 0:
    print('Freezing...')
elif 0 <= temp <= 20:
    print('Cold')
elif 21 <= temp <= 25:
    print('Normal')
elif 26 <= temp <= 35:
    print('Hot')
else:
    print('Very Hot!')
Normal

Imagine that in the above program, 23 is the temperature which was read by  some sensor or manually entered by the user and Normal is the response of the program.

If the code block is composed of only one line, it can be written after the colon:

if temp < 0: print 'Freezing...'

Since version 2.5, Python supports the expression:

<variable> = <value 1> if <condition> else <value 2>

Where <variable> receives <value 1> if <condition> is true and <value 2> otherwise.

4.1.2. Exercise 1#

Create some valid examples of using the conditional form introduced above.

4.2. Iteration#

Loops are repetition structures, generally used to process data collections iteratively, such as lines of a file or records of a database that must be processed by the same code block.

4.3. For loop#

A for loop[ is the repetition structure most often used in Python. The statement accepts not only static sequences, but also sequences generated by iterators. Iterators are structures that allow iterations, i.e. access to items of a collection of elements, sequentially.

During the execution of a for loop, the reference points to an element in the sequence. At each iteration, the reference is updated, in order for the for code block to process the corresponding element.

The clause break stops the loop and continue passes it to the next iteration. The code inside the else is executed at the end of the loop, except if the loop has been interrupted by break.

Syntax:

for <reference> in <sequence>:
    <code block>
    continue
    break
else:
    <code block>

4.3.1. Example 2#

# Sum 0 to 99
s = 0
for x in range(1, 100):
    s = s + x
print(s)
4950

The function range(m, n, p), is very useful in loops, as it returns a list of integers starting at m through smaller than n in steps of length p, which can be used as the order for the loop.

4.4. While loop#

The while loop executes a block of code in response to a condition.

Syntax:

while <condition>:
    <code block>
    continue
    break
else:
    <code block>

The code block inside the while loop is repeated while the loop condition is evaluated as true.

4.4.1. Example 3#

# Sum 0 to 99
s = 0
x = 1

while x < 100:
    s = s + x
    x = x + 1
print(s)
4950

4.4.2. Exercise 2#

Write an example of a nested for loop.

4.4.3. Exercise 3#

Write an example of a nested while loop.

4.4.4. Exercise 4#

Use help to find out what continue and break do.

help("break")
The "break" statement
*********************

   break_stmt ::= "break"

"break" may only occur syntactically nested in a "for" or "while"
loop, but not nested in a function or class definition within that
loop.

It terminates the nearest enclosing loop, skipping the optional "else"
clause if the loop has one.

If a "for" loop is terminated by "break", the loop control target
keeps its current value.

When "break" passes control out of a "try" statement with a "finally"
clause, that "finally" clause is executed before really leaving the
loop.

Related help topics: while, for
help("continue")
The "continue" statement
************************

   continue_stmt ::= "continue"

"continue" may only occur syntactically nested in a "for" or "while"
loop, but not nested in a function or class definition within that
loop.  It continues with the next cycle of the nearest enclosing loop.

When "continue" passes control out of a "try" statement with a
"finally" clause, that "finally" clause is executed before really
starting the next loop cycle.

Related help topics: while, for

4.5. Boolean expressions#

A boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two operands and produces True if they are equal and False otherwise.

5 == 5
True
5 == 6
False

True and False are special values that belong to the type bool; they are not strings.

== is just one of the python boolean operators. Here are the others.

  x != y               # x is not equal to y

  x > y                # x is greater than y
    
  x < y                # x is less than y

  x >= y               # x is greater than or equal to y
    
  x <= y               # x is less than or equal to y

There are also three logical operators, and, or, and not.
The semantics (meaning) of these operators is similar to their meaning in English.

For example, x > 0 and x < 10 is true only if x is greater than 0.

4.6. List comprehensions#

Python provides a convenient way of constructing lists using a for loop and and if statement. They are called list comprehensions and bear some similarity to the set builder notation that is commonly used in mathematical texts.

The general structure of a list comprehension is

newlist = [ for <item> in <iterable> if <expression>]

The iterable part is something in the python language that can be iterated over, for example, a list (there are other data types that can be iterated) over.

4.6.1. Example 4#

from math import sin
y = [sin(x) for x in range(10) if 4 < x and x < 8]
print(y)
[-0.9589242746631385, -0.27941549819892586, 0.6569865987187891]

4.6.2. Example 5#

from random import random
z = [random() for i in range(10)]
print(z)
[0.6688696438385179, 0.39000801218315084, 0.3768510669715849, 0.7141537145650474, 0.46344104202117165, 0.3405606196119375, 0.9229891249761667, 0.5759180767624973, 0.6835633711761102, 0.10494468553775294]

4.6.3. Example 6#

number_list = [ x for x in range(20) if x % 2 == 0]
print(number_list)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

4.6.4. Example 7#

obj = ["Even" if i%2==0 else "Odd" for i in range(10)]
print(obj)
['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']

4.6.5. Exercise 5#

What do you expect the output of the following to be ? What do you think the list A might represent ? And B ?

A = [[1, 2], [3,4], [5,6], [7,8]]
B = [[row[i] for row in A] for i in range(len(A[0]))]
print(B)
[[1, 3, 5, 7], [2, 4, 6, 8]]

4.6.6. Exercise 6#

Write some code to implement the last list comprehension in the previous exercise, without using list comprehensions.

B = []
A = [[1, 2],[3, 4],[5, 6],[7,8]]

for i in range(len(A[0])):
    transposed_row = []
    for row in A:
        transposed_row.append(row[i])
    B.append(transposed_row)

print(B)
[[1, 3, 5, 7], [2, 4, 6, 8]]