Program Flow and Structure#

There are tree main types of process flow structures:

  • Sequence

  • Branching

  • Iteration

Sequence#

Sequences are the simplest possible process-flow structure. A sequence is a list of explicit statements which are evaluated in exactly the same order such as:

a = 2
b = 1
c = a + b
d = c + 1
print(c)

Branching / Conditionals#

Branching splits the process flow into different possible branches each of which is only evaluated under certain conditions. In Python, we typically only use conditional branching of the form if: ...; elif: ...; else: ...;. The following code evaluates different branches depending on the value of n:

# n from earlier part of the software or from user input
if n == 0:
    a = - 1
elif (n % 2) == 0:
    a = - (5 ** n)
elif (n % 2) == 1:
    a = (-5) ** n
else:
    a = 0

Iteration#

f we want to repeat statements for a range of parameters or until a certain condition is met, we can use loops. Python offers the while and the for loop.

While loop#

While loops are used if we do not know the number of iterations before the evaluation. Example:

height = 10  # in m
timestep = 0.1  # in s
gravity = -9.81  # in m/s2
velocity = 0
while height > 0:
	height += velocity * timestep
	velocity += gravity * timestep
print("Hit the ground at {velocity} m/s.")

For loop#

For loops are used if the number of iterations to be performed is known before the evaluation. For example, we might want to iterate over all natural numbers between 0 and 100 and calculate their sum:

sum_natural_numbers = 0
for n in range(0, 101):
    sum_natural_numbers += n
print(sum_natural_numbers)

Skipping iterations: continue#

We can skip iterations with continue. To only sum over even numbers, between 0 and 100, we can do:

sum_even_natural_numbers = 0
for n in range(0, 101):
	if (n % 2) == 0:
	    continue
    sum_even_natural_numbers += n
print(sum_even_natural_numbers)

Stopping the iteration: break#

To stop an iteration at some point, we can use break:

height = 10  # in m
timestep = 0.1  # in s
gravity = -9.81  # in m/s2
velocity = 0
while height > 0:
	height += velocity * timestep
	velocity += gravity * timestep
	if abs(velocity) > 2:
	    break
print("Stopped evaluation at {height} m with {velocity} m/s.")

Useful functions#

We have seen the range() function for creating ranges of numbers. Other useful functions are

Enumeration#

enumerate() will enumerate all elements of a sequence:

for i, elem in enumerate(['a', 'b', 'c', 'd']):
    print(i, elem)
0 a
1 b
2 c
3 d

Zip#

zip() returns a sequence of corresponding elements from multiple sequences:

for n, v, a in zip(
    ('ham', 'spam', 'eggs'),
    ('is', 'was', 'has been'),
    ('good', 'mouldy', 'sticky'),
):
    print(n, v, a)
ham is good
spam was mouldy
eggs has been sticky

More#

There is the itertools module of the Python standard library, which provides many more functions for working with sequences. See the documentation for details.