from IPython.core.display import HTML

HTML(open("custom.html", "r").read())
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Copyright (C) 2014-2023 Scientific IT Services of ETH Zurich,
Contributing Authors: Uwe Schmitt, Mikolaj Rybniski

5. Python loops¶

Python has while:

  • if the condition after while is False from the beginning, skip the associated code block
  • else execute the code block and "jump back" to while.
  • check again
  • etc
i = 11

while i % 5 != 0:
    print(i)
    i = 2 * i + 1
11
23
47

and continue and break:

  • continue skips the end of the while code block and "jumps back" to while immediately
  • break stops looping and program execution continues after the while block
x = 9
while x > 0:
    x = x - 1
    if x % 2 == 0:
        continue  # skips rest of body of while
    print(x)
    if x % 3 == 0:
        break  # quit body of while

print("done")
7
5
3
done

No do until (or similar). Use while True: + break instead.¶

# draw random number in 0...1000 divisible by 7

import random

while True:

    # generate random integer in 0..1000 (limits included)
    number = random.randrange(0, 1001)
    if number % 7 == 0:
        break

    print("discard", number)

print("got", number)
discard 857
discard 831
discard 471
discard 981
discard 633
discard 16
discard 74
got 91

Quick intro Python lists¶

Python has some container types for collecting values. list is one such a type. We quickly introduce lists for the introduction of for-loops. More about lists later.

A list is an "expandable array", thus has no limited size (except you run out of memory).

li = [1, 2, 4, 8]
print(li)
[1, 2, 4, 8]

length of a list:

print(len(li))
4
print(type(li))
<class 'list'>

The empty list is []:

print(type([]))
print(len([]))
<class 'list'>
0

List of strings:

li = ["hi", "ho"]

Mixed types:

li = [1, 2.0, True, "hi"]
print(li)
[1, 2.0, True, 'hi']

for loops¶

for has the general form

for <variable> in <iterable>:
    <codeblock>

An example for such an iterable are lists:

for name in ["urs", "uwe", "guido"]:
    print("I say hi to", name)

print("I also say hi to everybody I forgot")
I say hi to urs
I say hi to uwe
I say hi to guido
I also say hi to everybody I forgot

Here name is a variable which you can name as you like.

In the first iteration name is urs, in the second iteration name is uwe, in the third iteration name is guido. Then the list is exhausted and iteration stops.

Here we iterate over a list of numbers to sum them up:

def sumup(numbers):

    # "sum" is a built-in Python function, so we append "_" to avoid
    # overlap:

    sum_ = 0.0
    for number in numbers:
        sum_ = sum_ + number
    return sum_


print(sumup([1, 2, 3]))
6.0

In the previous example number takes values 1, 2, and 3. And sum_ starts with 0 and then is updated to 1, 3 and 6.

"Classic" countint loops are not so often required in Python. But if you need them you can use the range function which returns an so-called "iterable":

for i in range(4):
    print(i, "squared is", i * i)
0 squared is 0
1 squared is 1
2 squared is 4
3 squared is 9

Now with different starting value:

for i in range(1, 4):
    print(i, "squared is", i * i)
1 squared is 1
2 squared is 4
3 squared is 9

And with a step size:

for i in range(1, 4, 2):
    print(i, "squared is", i * i)
1 squared is 1
3 squared is 9

Antipattern (C style)

This is correct code, and correlates to the way you iterate in some other languages like C:

numbers = [1, 3, 5]
for i in range(len(numbers)):
    print(numbers[i])
1
3
5

The more "pythonic" and thus more readable version is:

for number in numbers:
    print(number)
1
3
5

The range function returns an iterable:

print(range(1, 4))
range(1, 4)

To see what an iterable produces (and thus how it behaves when used in a for loop), you can pass it to the list funtion which converts an iterable to the list of the values the iterable produces:

print(list(range(1, 4)))
[1, 2, 3]

Comment: Python also has some INFINITE iterators, so be prepared!

Exercise block 5¶

  1. Reread examples above carefully.
  2. Type, run and try to understand the sumup example.
  3. What do you think will happen if you loop with for over a string? What is the result if you pass a string to list()? Try it out.

Check question¶

  1. Use pen and paper to determine the final value of z in the following program:

    x = list(range(5))
    z = 0
    for i in x:
        z += i
    
    while z > 0:
        if z % 5 == 0:
            z = 3
            continue
        z //= 2
    
    
  2. Can you write shorter expressions for range(0, 3) and range(1, 4, 1) ?

Programming exercises¶

  1. Write a function average which takes a list of numbers and computes their average (extend the example for summing up numbers).

  2. Make sure that the program returns None if the list of numbers is empty.

  3. Write a function which takes a list of strings and appends them all. E.g.

    append(["a", "bc", "def"]) == "abcdef"
    

Optional programming exercises*¶

  1. import random, lookup function random.random and implement https://academo.org/demos/estimating-pi-monte-carlo/
  2. Write a function which tests if a given number is prime.

Homework¶

  1. Modify the previous average function to compute the average of all even numbers in the list. You also have to count the even numbers for this(!).

Optional homework*¶

  1. The collatz-conjecture (https://en.wikipedia.org/wiki/Collatz_conjecture) is based on the following scheme:

    1. start with a number n.
    2. in case n is even replace n by n/2
    3. else replace n by 3n + 1.
    4. in case n is not 1 continue with step B.

    Write a function collatz(n) which prints the values of n during this iteration scheme.