Week 8: Python Time to Guess

Review

  • Mathematical operators
  • Lists

Discussion

  • While loops
    • Repeat a section of code an unknown number of times until a condition is met.

      while condition: statement(s)
    • We use for loops when we know exactly how many times we want to execute a block of code (i.e. 10 times to create a snowflake with 10 arms).
    • While loops are used when we don’t know how many times we will need to execute a task.
      • i.e. If we ask a user to guess a number between 1 and 10, we don’t know how many times they will guess incorrectly. So, we continue to ask the user to guess a number, while the number is not correct.
    • Infinite loops, when the condition is never false. This may crash a program, so you want the condition to become false at some point.
    • Using a while loop to receive correct input:
      • Ask the user for input
      • While the input is incorrect
      • Ask the user for another value
      • Go back to (2)

Lesson

Guessing Game
number = 7
guess = input(“Guess a number between 1 and 10”)

while int(guess) != number:

guess = input(“Guess again”)

print(“Congratualations!”)
Guess a number between Guess again 7
Congratulations!
1and105

Practice

  • Create your own guessing game.
    • Ask the user for their name and introduce them to the game.
    • Use the while loop structure, taking input from the user and checking it against some condition.
    • Congratulate the user when they’ve won.
  • Extend your guessing game. For example..
    • Ask the user for a difficulty level (easy – guess a number between 1 and 10; medium – 1 and 20; hard – 1 and 50)
      difficulty = input("Enter a level of difficulty - easy/medium/hard")
      if difficulty == "easy": max = 10
      elif difficulty == "medium": max = 20
      elif difficulty == "hard": max = 50

      number = random.randint(1, max)

    • ⦁ When the user guesses incorrectly, give them a hint by telling them whether their answer is too high or too low.