While Loops Introduction to Python Introduction to Python
- Slides: 11
While Loops Introduction to Python
Introduction to Python L 5 While Loops 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
Introduction to Python L 5 While Loops Structure of a While loop Condition If condition is true Conditional Code If condition is false
Introduction to Python L 5 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 L 5 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 L 5 While Loops Example 2: While loop pseudocode Count 0 Running. Total 0 input Number while Number <> 0 Count + 1 Running. Total + Number input next number end while loop display "You entered " Count "numbers" display "Total = " Running. Total
Introduction to Python L 5 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 L 5 While Loops IF Statements inside While Loops! input password attempts = 0 while attempts not equal to 3 enter password 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 L 5 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 L 5 While Loops Plan your code • Use pseudocode to help you plan your game.
Introduction to Python L 5 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)