0% found this document useful (0 votes)
1 views1 page

Simple Loops - Python Programming MOOC 2025

Uploaded by

cyw4691
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views1 page

Simple Loops - Python Programming MOOC 2025

Uploaded by

cyw4691
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Chen Ye Wu Log out

Part 2

Simple loops
Learning objectives

After this section

You will know what a loop means in programming


You will be able to use a while True loop in your programs
You will know how to use the break command to break out of a loop

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!")

About this course


Running the program could look like this:
Grading and exams Sample output

Please type in a number, -1 to quit: 2


All exercises
4
Please type in a number, -1 to quit: 4
Introduction to Programming
exam 19.07. 16
Please type in a number, -1 to quit: 10
Support and assistance 100
Please type in a number, -1 to quit: -1
Frequently asked questions
Thanks and bye!

Common error messages

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

number = int(input("Please type in a number, -1 to quit: "))


Part 5
while True:
if number == -1:
Part 6
break

Part 7
print(number ** 2)

Advanced Course in Programming print("Thanks and bye!")

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")

print("Correct PIN entered!")

Sample output

Please type in your PIN: 0000


Incorrect...try again
Please type in your PIN: 9999
Incorrect...try again
Please type in your PIN: 1234
Correct PIN entered!

Programming exercise: Points:

Shall we continue? 1/1

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

1 # Write your solution here


2
3 while True:
4 print('hi')
5 inputfromUser = input(('Shall we continue? '))
6
7 if inputfromUser == 'no' :
8 break
9
10 print('okay then')
11
12

RUN TEST Reset Model solution

Submissions Results Need help? Close

Points awarded: 2.shall_we_continue

Show all 100 %

Programming exercise: Points:

Input validation 1/1

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

An example of expected behaviour of your program:

Sample output

Please type in a number: 16


4.0
Please type in a number: 4
2.0
Please type in a number: -3
Invalid number
Please type in a number: 1
1.0
Please type in a number: 0
Exiting...

1 from math import sqrt


2 # Write your solution here
3
4 while True:
5 number = int(input('Please type in a number: '))
6
7 if number < 0 :
8 print('Invalid number')
9
10 if number > 0 :
11 print(sqrt(number))
12
13 if number == 0 :
14 print('Exiting...')
15 break
16
17

RUN TEST Reset Model solution

Submissions Results Need help? Close

Points awarded: 2.input_validation

Show all 100 %

Programming exercise: Points:

Fix the code: Countdown 1/1

This program should print out a countdown. The code is as follows:

number = 5
print("Countdown!")
while True:
print(number)
number = number - 1
if number > 0:
break

print("Now!")

This should print out

Sample output

Countdown!
5
4
3
2
1
Now!

However, the program doesn't quite work. Please fix it.

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

RUN TEST Reset Model solution

Submissions Results Need help? Close

Points awarded: 2.countdown

Show all 100 %

Programming exercise: Points:

Repeat password 1/1

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.

Have a look at the expected behaviour below:

Sample output

Password: sekred
Repeat password: secret
They do not match!
Repeat password: cantremember
They do not match!
Repeat password: sekred
User account created!

1 # Write your solution here


2
3
4
Exercise completed, congratulations!
password = input('Password: ')
×
5 while True:
6 Points awarded:
repeatedPasswprd = input('Repeat Password: ')
2.repeat_password
7
8 if repeatedPasswprd == password:
9 Close
print('User account created!') View model solution
10 break
11
12 print('They do not match!')

RUN TEST Reset Model solution

Submissions Results Need help? Close

Points awarded: 2.repeat_password

Show all 100 %

Loops and helper variables


Let's make the PIN checking example a bit more realistic. This version gives the user
only three attempts at typing in a PIN.

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

Please type in your PIN: 0000


Incorrect...try again
Please type in your PIN: 1234
Correct PIN entered!

Sample output

Please type in your PIN: 0000


Incorrect...try again
Please type in your PIN: 9999
Incorrect...try again
Please type in your PIN: 4321
Too many attempts...

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.

Debugging print statements in loops


Adding loops to programs also adds to the potential sources of bugs. It becomes even
more important to master the use of debugging print statements as introduced in the
first section of this part.

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

Please type in your PIN: 0000


Incorrect...try again
Please type in your PIN: 9999
Incorrect...try again
Please type in your PIN: 1234
Too many attempts...

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

beginning of the while block:


Please type in your PIN: 2233
attempts: 1
condition1: False
code: 2233
condition2: False
Incorrect...try again
beginning of the while block:
Please type in your PIN: 4545
attempts: 2
condition1: False
code: 4545
condition2: False
Incorrect...try again
beginning of the while block:
Please type in your PIN: 1234
attempts: 3
condition1: True
Too many attempts...

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:
# ....

# this block is executed too early


if attempts == 3:
success = False
break

# the third iteration never gets this far


if code == "1234":
success = True
break

The order of conditional statements, or of different branches within a conditional


statement, is a common cause for bugs, especially in loops. Debugging print
statements are often the simplest way of finding their cause.

Programming exercise: Points:

PIN and number of attempts 1/1

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')

RUN TEST Reset Model solution

Submissions Results Need help? Close

Points awarded: 2.pin_and_number_of_attempts

Show all 100 %

You might also like