0% found this document useful (0 votes)
194 views11 pages

Chapter Loops

The document discusses different types of loops in programming including while loops. It provides examples of while loops that repeat code until a condition is met, such as the user inputting a target value like -1. It also discusses using loops to limit the number of attempts at a task before terminating the loop. Helper variables are introduced to track values like the number of attempts. The document provides exercises for readers to write loops that iterate in different controlled ways.

Uploaded by

Ranim Guith
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)
194 views11 pages

Chapter Loops

The document discusses different types of loops in programming including while loops. It provides examples of while loops that repeat code until a condition is met, such as the user inputting a target value like -1. It also discusses using loops to limit the number of attempts at a task before terminating the loop. Helper variables are introduced to track values like the number of attempts. The document provides exercises for readers to write loops that iterate in different controlled ways.

Uploaded by

Ranim Guith
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/ 11

Chapter

Loops

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.

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

if number == -1:
break

print(number ** 2)

print("Thanks and bye!")

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

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:
Shall we continue?
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
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 three attempts
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.

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!

Concatenating strings with the + operator


The above example with PIN checking used a helper
variable attempts to keep track of how many times the user had tried
to type in a code:

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.

A similar idea of incrementation works with string variables as well.


The program could, for instance, keep track of all the PIN codes the
user typed in:

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:

code = input("Please type in your PIN: ")


codes += code + ", "
If the user types in the codes 1111 2222 1234, at the end of the
program's execution the value of codes would be

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.

number = int(input("Please type in a number: "))

while number < 10:


print(number)
number += 1

print("Execution finished.")

This could print out:

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.

The beginning of your output should look like this:

Sample output
2 4 6 8 etc...

Programming exercise:
Fix the code: Countdown
The program below has some syntactic issues:

print("Are you ready?")


number = int(input("Please type in a number: "))
while number = 0:
print(number)
print("Now!")
Please fix it so that it prints out the following:

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:

number = int(input("Please type in a number: "))

while number < 100 and number % 5 != 0:


print(number)
number += 3

Two examples of the program's execution with different inputs:

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:

number = int(input("Please type in a number: "))

while number != 10:


print(number)
number += 2
If the input is an even number and equals 10 or less, the loop will
terminate:

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!

You might also like