4-1-while-loops
4-1-while-loops
ondon omputing
Programming for
GCSE
Topic 4.1: While
Loops
William Marsh
School of Electronic Engineering and Computer Science
Queen Mary University of London
Aims
counter = 1
while counter <= 5:
print("Inside the loop")
counter = counter + 1
Key
word Conditio
n :
indentatio
n
Boxes
while condition A:
Renter the box while 'A’ is true
Using a Counter
counter = 1 test
while counter <= 5:
print("Inside the loop")
counter = counter + 1
increment
Quiz: Counter Values
counter = 7
while counter <= 15:
print("Inside the loop")
counter = counter + 2
Quiz: Counter Values
counter = 7
while counter <= 15:
print("Inside the loop")
counter = counter + 2
Counter Print
7 "Inside the loop"
9 "Inside the loop"
11 "Inside the loop"
13 "Inside the loop"
15 "Inside the loop"
17 -
Varying the Code
Repeated
• Previously, same code repeated
• Use counter to make it vary
counter = 1
while counter < 6:
print(”The counter is”, counter)
counter = counter + 1
Varying the Code
Repeated
counter = 1
while counter < 6:
print(”The counter is”, counter)
counter = counter + 1
Counter Print
1 The counter is 1
2 The counter is 2
3 The counter is 3
4 The counter is 4
5 The counter is 5
6 -
Varying the Code
Repeated
cntr = 1
while cntr < 6:
if cntr % 2 == 0 :
print(”The counter is”, cntr)
cntr = cntr + 1
Counter Print
1
2 The counter is 2
3
4 The counter is 4
5
6 -
Order Matters
• These two programs differ
• Can you explain how?
counter = 1
while counter < 6:
print(”The counter is”, counter)
counter = counter + 1
counter = 1
while counter < 6:
counter = counter + 1
print(”The counter is”, counter)
Errors
cntr = 1
while cntr < 6:
if cntr % 2 == 0 :
print(”The counter is”, cntr)
cntr = cntr + 1
Counter Loops –
Summary
• Counter
• Initialise it
• Test it
• Change it
• The counter has a sequence of values
in the loop body
• The counter value can be used to vary
the statement executed each time
through the loop
COMPARISONS
Loops in Scratch
• Scratch has 4 loops
Loop without end
Loop fixed
number of
time
Conditi
on
Loop while condition true
Conditi
on
Loop until condition true
’While’ Language
• Many instructions have ‘loop’ language
needAnswer = True
while needAnswer :
ans = input(”Answer Yes or No! ")
if ans == “Yes” or ans == “No”:
needAnswer = False
Answer Yes or No! Not sure
Answer Yes or No! Ok
Answer Yes or No! Will do
Answer Yes or No! I said alright
Answer Yes or No! Yes
Childhood Classic