Chapter Loops
Chapter Loops
Loops
while loop
Example1:
while True:
number = int(input("Please type in a number, -1 to quit: "))
if number == -1:
break
print(number ** 2)
Sample output
Please type in a number, -1 to quit: 2
4
Please type in a number, -1 to quit: 4
16
Please type in a number, -1 to quit: 10
100
Please type in a number, -1 to quit: -1
Thanks and bye!
Example2:
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
hi
Shall we continue? yes
hi
Shall we continue? oui
hi
Shall we continue? jawohl
hi
Shall we continue? no
okay then
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
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.
Programming exercise:
PIN and number of attempts
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!
attempts = 0
while True:
code = input("Please type in your PIN: ")
attempts += 1
# ...
The variable is set to zero outside the loop, and each iteration
increases its value by one.
codes = ""
attempts = 0
while True:
code = input("Please type in your PIN: ")
attempts += 1
codes += code + ", "
# ...
The helper variable is initialized to an empty string, that is, a string with
no characters in it:
codes = ""
With each iteration the string gets longer, as the code the user typed
in is added, along with a comma:
Sample output
1111, 2222, 1234,
Programming exercise:
Story
Part 1
Please write a program which keeps asking the user for words. If the
user types in end, the program should print out the story the words
formed, and finish.
Sample output
Please type in a word: Once
Please type in a word: upon
Please type in a word: a
Please type in a word: time
Please type in a word: there
Please type in a word: was
Please type in a word: a
Please type in a word: girl
Please type in a word: end
Once upon a time there was a girl
Part 2
Change the program so that the loop ends also if the user types in the
same word twice.
Loops with conditions
The general structure of the while statement is as follows:
while <condition>:
<block>
In the following loop we have the condition number < 10. The block
within the loop is executed only if the variable number is less than 10.
print("Execution finished.")
Sample output
Please type in a number: 4
4
5
6
7
8
9
Execution finished.
Initialisation, condition and update
If any one of these three components is missing, the loop will likely
not function correctly.
Programming exercise:
Print numbers
Please write a program which prints out all the even numbers
between two and thirty, using a loop. Print each number on a
separate line.
Sample output
2 4 6 8 etc...
Programming exercise:
Fix the code: Countdown
The program below has some syntactic issues:
Sample output
Are you ready? Please type in a number: 5 5 4 3 2 1 Now!
Writing conditions
Any Boolean expression or combination thereof is a valid condition in
a loop. For example, the following program prints out every third
number, but only as long as the number is less than 100 and not
divisible by 5:
Sample output
Please type in a number: 28
28
31
34
37
Sample output
Please type in a number: 96
96
99
When the input is 28, the loop ends with the number 37, because the
next number is 40, which is divisible by 5. When the input is 96, the
loop ends with the number 99, because the next number is 102,
which is not less than 100.
Whenever you write a loop you should make sure that the execution
of the loop will always end at some point. The following program
either finishes or doesn't, depending on the input:
Sample output
Please type in a number: 4
4
6
8
In any other case the loop gets executed endlessly, as there is no way
the variable could then ever equal 10. For example 3 or 12 are inputs
that would end in an infinite loop.
Programming exercise:
Numbers
Please write a program which asks the user for a number. The
program then prints out all integer numbers greater than zero but
smaller than the input.
Sample output
Upper limit: 5
1
2
3
4
Please don't use the value True as the condition of your while loop in
this exercise!