Simple Loops - Python Programming MOOC 2025
Simple Loops - Python Programming MOOC 2025
Part 2
Simple loops
Learning objectives
We have now covered conditional structures in some detail. Another central technique
in programming is repetition, or iteration. Together these form the fundamental
control structures any programmer must master. They are called control structures
because essentially they allow you to control which lines of code get executed when.
While conditional structures allow you to choose between sections of code, iteration
structures allow you to repeat sections of code. They are often called loops because
they allow the program to "loop back" to some line that was already executed before.
The process of executing one repetition of a loop is also referred to as an iteration of
the loop.
This section introduces a simple while loop. Its structure is similar to the conditional
statements we already covered. In the next part we will delve into some more
sophisticated examples.
Let's have a look at a program which asks the user to type in a number and then
prints out the number squared. This continues until the user types in -1.
while True:
number = int(input("Please type in a number, -1 to quit: "))
if number == -1:
break
print(number ** 2)
Python Programming MOOC
2025 print("Thanks and bye!")
As you can see above, the program asks for several numbers, thanks to the while
Introduction to Programming
statement in the program. When the user types in -1, the break command is
Part 1 executed, which exits the loop and execution continues from the first line after the
while block.
Part 2
With loops, it is crucial that there is always a way to exit the loop at some point in the
Part 3 code, otherwise the repetition could go on forever. To illustrate this, let's change the
above example a little:
Part 4
Part 7
print(number ** 2)
Part 8
In this version the program asks the user to type in a number outside the loop. If the
Part 9
user types in any other number than -1, the loop is never exited from. This forms an
Part 10
infinite loop, which means the block of code within the loop is repeated endlessly:
Sample output
Part 11
Please type in a number, -1 to quit: 2
4
Part 12
4
Part 13 4
4
Part 14 4
4
4
4
(continued ad infinitum...)
The following program has a similar structure to the example above the infinite loop,
but the user experience is quite different. This program allows the user to proceed
only if they type in the correct PIN 1234:
while True:
code = input("Please type in your PIN: ")
if code == "1234":
break
print("Incorrect...try again")
Sample output
Let's create a program along the lines of the example above. This program
should print out the message "hi" and then ask "Shall we continue?" until the
user inputs "no". Then the program should print out "okay then" and finish.
Please have a look at the example below.
Sample output
hi
Shall we continue? yes
hi
Shall we continue? oui
hi
Shall we continue? jawohl
hi
Shall we continue? no
okay then
Please write a program which asks the user for integer numbers.
If the number is below zero, the program should print out the message
"Invalid number".
If the number is above zero, the program should print out the square root of
the number using the Python sqrt function.
In either case, the program should then ask for another number.
If the user inputs the number zero, the program should stop asking for
numbers and exit the loop.
Below you'll find a reminder of how the sqrt function is used. Remember to
import it in the beginning of the program.
# sqrt function will not work without this line in the beginning of the prog
from math import sqrt
print(sqrt(9))
Sample output
3.0
Sample output
number = 5
print("Countdown!")
while True:
print(number)
number = number - 1
if number > 0:
break
print("Now!")
Sample output
Countdown!
5
4
3
2
1
Now!
1 number = 5
2 print("Countdown!")
3 while True:
4 print(number)
5 number = number - 1
6 if number <= 0:
7 break
8
9 print("Now!")
10
Please write a program which asks the user for a password. The program
should then ask the user to type in the password again. If the user types in
something else than the first password, the program should keep on asking
until the user types the first password again correctly.
Sample output
Password: sekred
Repeat password: secret
They do not match!
Repeat password: cantremember
They do not match!
Repeat password: sekred
User account created!
The program uses two helper variables. The variable attempts keeps track of how
many times the user has typed in a PIN. The variable success is set to either True or
False based on whether the user is successful in signing in.
attempts = 0
while True:
code = input("Please type in your PIN: ")
attempts += 1
if code == "1234":
success = True
break
if attempts == 3:
success = False
break
# this is printed if the code was incorrect AND there have been less than t
print("Incorrect...try again")
if success:
print("Correct PIN entered!")
else:
print("Too many attempts...")
Sample output
Sample output
The loop is exited either when the user types the correct PIN or if there have been too
many attempts. The if statement after the loop checks the value of the variable
success and prints out a message accordingly.
Let's have a look at a program almost identical to the previous example, but with one
crucial difference:
attempts = 0
while True:
code = input("Please type in your PIN: ")
attempts += 1
if attempts == 3:
success = False
break
if code == "1234":
success = True
break
print("Incorrect...try again")
if success:
print("Correct PIN entered!")
else:
print("Too many attempts...")
This version acts strangely when the user types in the correct code on the third
attempt:
Sample output
So, let's try and find the cause by adding some strategic debugging print statements
inside the loop:
while True:
print("beginning of the while block:")
code = input("Please type in your PIN: ")
attempts += 1
print("attempts:", attempts)
print("condition1:", attempts == 3)
if attempts == 3:
success = False
break
print("code:", code)
print("condition2:", code == "1234")
if code == "1234":
success = True
break
print("Incorrect...try again")
Sample output
From the above printouts we can see that during the third iteration of the loop the
condition of the first if statement is True , and the loop is exited. This iteration never
gets to the second if statement, which checks whether the code was typed in
correctly:
while True:
# ....
Please write a program which keeps asking the user for a PIN code until they
type in the correct one, which is 4321. The program should then print out the
number of times the user tried different codes.
Sample output
PIN: 3245
Wrong
PIN: 1234
Wrong
PIN: 0000
Wrong
PIN: 4321
Correct! It took you 4 attempts
If the user gets it right on the first try, the program should print out something
a bit different:
Sample output
PIN: 4321
Correct! It only took you one single attempt!
2
3 attempts = 0
4
5 while True:
6 PIN = int(input('PIN: '))
7 attempts += 1
8
9 if PIN == 4321 and attempts == 1 :
10 print('Correct! It only took you one single attempt!')
11 break
12
13 if PIN == 4321 :
14 print(f'Correct! It took you {attempts} attempts')
15 break
if PIN != 4321 :
16
17 if PIN != 4321 :
18 print('Wrong')