



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
These lecture notes from cpsc 121 (fall 2012) cover the topic of while loops in python and include examples of implementing a guessing game. The notes also include exercises for the students to practice.
Typology: Study notes
1 / 6
This page cannot be seen from the preview
Don't miss anything!




Today ...
Homework
Reading
Consider this simple function:
def guess_color(): c = randint(1,2) g = input("What’s your favorite color (1=red, 2=blue)? ") if int(g) == c: print("Right. Off you go.") else: print("Auuuuuuuugh")
What if we wanted to loop until the correct color was entered?
While statement syntax
while boolean condition: statement statement ...
Q: How would you draw a flow chart for this?
Condi&on (while) Statement
False
True
Statement
Write a function guessing game(low, high) that plays one round of a number guessing game (i.e., guess a number between 1 and 10 if low is 1 and high is 10). Your function should work like this:
guessing_game(1, 10) Please guess a number between 1 and 10: 4 Sorry, the correct answer was: 2 guessing_game(1, 3) Please guess a number between 1 and 10: 3 You guessed it!
The number to guess should be randomly generated by the function.
Answer...
def guessing_game(low, high): n = randint(low, high) s = "Please guess a number between " +str(low) + " and " + str(high) + ": " g = int(input(s)) if g == n: print("Sorry, the correct answer was:", n) else: print("You guessed it!")