Docsity

Lecture Notes for CPSC 121 Fall 2012: While Loops and Guessing Games, Study notes of Computer Science

Partial preview of the text

Download Lecture Notes for CPSC 121 Fall 2012: While Loops and Guessing Games and more Study notes Computer Science in PDF only on Docsity!

Today ...

  • Quiz 6
  • While Loops
  • Exercises

Homework

  • HW 9 due
  • HW 10 out

Reading

  • Ch 6, 8

While loops

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?

  • Can you think of a way to use a Python for loop here?
  • We need a new type of loop!

While statement syntax

while boolean condition: statement statement ...

  • As long as the boolean condition evaluates to True
  • Execute the body of the while statement
  • Otherwise, skip the body of the while

Q: How would you draw a flow chart for this?

  • Flow charts often used for while statements ...

Condi&on (while) Statement

False

True

Statement

Exercise

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!")