Before session 4
Loops and iterations
Work through topics from the reading materials or watch the videos.
Test
Go to Moodle and take the fourth test.
Homework
The deadline for homework is Monday. Nevertheless, you can start with homework already before the session.
This week we are going to get an insight into loops (while and for).
Example 1
In many cases, it is possible to solve an exercise using both the while and for loops. The following programs calculate the sum of the figures from 1 to 9. The first program contains the for-loop and the second one uses the while-loop.
print("Finding sum with for loop") sum1 = 0 for i in [1,2,3,4,5,6,7,8,9]: sum1 = sum1 + i print("Sum so far", sum1) print("Sum of numbers 1-9 is", sum1) print("Finding sum with while loop") sum2 = 0 a = 1 while a < 10: sum2 = sum2 + a print("Sum so far", sum2) a += 1 print("Sum of numbers 1-9 is", sum2)
Example 2
The following program is a modified example from last week - The maximum program. The present program contains a loop which repeatedly asks the user for numbers and outputs the greatest of these numbers. The program continues asking until the user enters “done” instead of the first number. If the user enters something else but integers, the program processes the error using try and except, prints out a message and skips to the next number.
def maximum(a, b): if a < b: return b else: return a while True: line = input("Enter the first number or word 'done': ") if line == 'done': break line2 = input("Enter the second number: ") try: x = int(line) y = int(line2) m = maximum(x, y) print("The maximum of numbers", x, "and", y, "is", m) except: print("Please enter a number")