Transcript While Loops

While Loops
Introduction to Python
Introduction to Python
L5 While Loops
Learning Objectives
• All to use a while loop in a program
• Most to use an if statement within a while
loop
• Some to use a function to generate a random
number
Introduction to Python
L5 While Loops
Structure of a While loop
Condition
If condition
is true
Conditional Code
If condition
is false
Introduction to Python
L5 While Loops
Example 1: While Loop pseudocode
‘Nagging’ Example
print “Mum, can I have an ice cream?”
input answer
while answer is “No”
print “Please can I have an ice cream?”
input answer
end while loop
print “Thank you!”
Introduction to Python
L5 While Loops
While Loop Syntax
#Quiz Question
answer = input("What is the capital of France?")
answer = answer.title()
while answer != "Paris":
answer = input("Incorrect, try again: ")
answer = answer.title()
print("Correct! Well done.")
Introduction to Python
L5 While Loops
Example 2: While loop pseudocode
Count  0
RunningTotal  0
input Number
while Number <> 0
Count  Count + 1
RunningTotal  RunningTotal + Number
input next number
end while loop
display "You entered " Count "numbers"
display "Total = " RunningTotal
Introduction to Python
L5 While Loops
Adding a Counter Variable
• Add a Counter variable to say how many times
the user attempted the question
answer = input("What is the capital of France?")
answer = answer.title()
counter = 1
while answer != "Paris":
answer = input("Incorrect, try again: ")
answer = answer.title()
counter = counter + 1
print("Correct! You had ",counter,“attempts.")
Introduction to Python
L5 While Loops
IF Statements inside While Loops!
input password
attempts = 0
while attempts not equal to 3
enter password
attempts  attempts + 1
if password correct then
display entry screen
attempts = 3
else
display “Password Incorrect”
if password incorrect
Print “You are locked out.”
Introduction to Python
L5 While Loops
Guess My Number!
• Create a computer game where the
computer generates a random number
between 1 and 100 and you have to guess
the number.
• The game should keep a record of how many
attempts you took.
• The computer should tell you whether you
are too high, too low or correct with each
guess.
Introduction to Python
L5 While Loops
Plan your code
• Use pseudocode to help you plan your game.
Introduction to Python
L5 While Loops
Random Number Module
• Use the following syntax:
#Import the random number module
import random
#Generate a random number between 1
and 10
number = random.randint(1,10)
Introduction to Python
L5 While Loops
Finally…
• Complete the plenary questions to show me
what you have learnt today.