Closure#
Syllabus Week 4: Loops#
Looping over a sequence (known number of iterations), keyword
for
and keywordin
, therange()
functionUnderstanding that indexing variable in the for loop is reassigned with each iteration
Looping as long as a condition is true (unknown number of iterations), keyword
while
Understanding that the variables used in the condition need to be defined before the while loop
Understanding that the variables used in the condition should be changed in the while loop body for loop to terminate
Keyword
break
Solve simple problems that require a lot of computation e.g. simulations and population models
The concept of pseudocode
Advanced#
Advanced 4.1: Keyword continue
#
Run this code which shows how you can use the keyword continue
to skip the rest of the code block and continue with the next iteration of the loop.
for i in range(10):
if i == 5:
continue
print(i)
Advanced 4.2: Walrus Operator#
Experienced programmers often seek ways of making code more compact, and Python offers features allowing this. For example, the walrus operator :=
does two things at once: it assigns a value to a variable (similar to assignment operator =
) and it also evaluates the expression. Since it evaluates the expression, it may be in a conditional statement.
Look at the simple example of using walrus operation.
print(name := "John")
print(f"Hello, ", name)
And here you can see how it may be used in a conditional statement.
name = "Bartholomew"
if is_long := len(name) > 10:
print(f"Wow, the name is long!")
print(f"Value of is long: {is_long}")
If you want to know why the operator is called the walrus operator, the image below might give you a hint.
Advanced 4.3: Using _
as Variable Name#
Check this code.
for _ in range(3):
print("Hello!")
In Python, is common to use _
as the name for the variable which will not be used later. For example, if the iteration variable is not used in the loop. There is nothing special about the _
variable name in Python, and using it is just a convention.
Advanced 4.4: Why Does It Stop?#
You know from mathematics that if you halve a positive number, the result will still be positive. Repeated halving should approach, but never reach zero. Try now to run the following code, and give it some time to finish executing.
x = 5
while x > 0:
print(x)
x = x/2
The code execution stops because at some point x
becomes so small that it cannot be represented accurately as a floating-point number. This is something to keep in mind when working with very small or very large floating-point numbers. Do you think the loop would keep running if the condition of the while loop was x != 0
?
Run the code below which compares two numbers which should be the same.
a = (1 ** 50) / (200 ** 50)
b = (1 / 200) ** 50
print(a == b)
The result is False
rounding errors when using floating-point numbers. Therefore, if you want to check whether two floating-point are equal, you should check if the absolute difference between them is smaller than some threshold, as shown below.
a = (1 ** 50) / (200 ** 50)
b = (1 / 200) ** 50
print(abs(a - b) < 1e-10)
Advanced 4.5: Efficient Looping#
It is good coding practice to avoid unnecessary calculations inside loops. This is especially important if the loop is executed many times. Consider the following code which computes the volume of water in a cylinder for different heights. The formula for the volume is given by
where \(r\) is the radius and \(h\) is the height of the cylinder.
import math
for height in range(1, 6):
pi = math.pi
radius = 0.8
volume = pi * (radius ** 2) * height
print("Volume is", volume, "for height", height)
This code gives correct result, but may be improved. Assigning constants pi
and radius
may be done only once before the loop, instead of once in each iteration. Furthermore, a part of the calculation can be moved outside the loop, since only the value of h
changes. If you calculate the area of the base of the cylinder \(2 \pi \, r^2\) before the loop you can reuse it in each iteration. Make those changes!
Advanced 4.6: How Many Guesses?#
How many guesses do you need to find a number between 1 and 100? The code below will help you to find out.
import random
print(21 * "*~")
print(' WELCOME TO "HOW MANY GUESSES"!')
print(21 * "*~")
print("To exit the gama at any time, press Enter")
print("without typing anything.")
number = random.randint(1, 100)
guess = -1
tries = 0
while guess != number:
tries += 1
print("Try", tries)
answer = input("Guess a number between 1 and 100: ")
if answer =="":
print("Bye!")
break
guess = int(answer)
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
else:
print("You guessed it! Tries used:", tries)
*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~
WELCOME TO "HOW MANY GUESSES"!
*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~
To exit the gama at any time, press Enter
without typing anything.
Try 1
Too low!
Try 2
Too low!
Try 3
Too high!
Try 4
Too high!
Try 5
Too high!
Try 6
You guessed it! Tries used: 6