You are on page 1of 12

While loops

Introduction to Python
Learning objectives
• Use a while loop in a program
• Use an if statement within a while loop
• Use a function to generate a random number
Homework
What is pseudocode?
• Write the meaning? And see if you can find an
example.
Introduction to Python
While loops

Structure of a While loop


• L5 While Loops
• L5 While Loops If condition
is false
Condition

If condition
is true

Conditional Code
Introduction to Python
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
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
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
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
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
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
While loops

Plan your code


• Use pseudocode to help you plan your game
Introduction to Python
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)

You might also like