exercises

high-low part 7

Modify hilo.py so it will only keep asking the user to guess if they haven’t guessed right yet and if they haven’t run out of guesses:

>>> %Run hilo.py 
you have 7 guesses left
Pick a number: 50
Your guess is too low.
you have 6 guesses left
Pick a number: 75
Your guess is too low.
you have 5 guesses left
Pick a number: 88
Your guess is too low.
you have 4 guesses left
Pick a number: 95
Your guess is too high.
you have 3 guesses left
Pick a number: 92
Your guess is too high.
you have 2 guesses left
Pick a number: 91
You got it right!
>>> %Run hilo.py 
you have 7 guesses left
Pick a number: 1
Your guess is too low.
you have 6 guesses left
Pick a number: 2
Your guess is too low.
you have 5 guesses left
Pick a number: 3
Your guess is too low.
you have 4 guesses left
Pick a number: 4
Your guess is too low.
you have 3 guesses left
Pick a number: 5
Your guess is too low.
you have 2 guesses left
Pick a number: 6
Your guess is too low.
you have 1 guesses left
Pick a number: 7
Wrong! The number was 10

Show solution

import random
guesses_left = 7
computer_number = random.randint(1, 100)

print("you have", guesses_left, "guesses left")
guess = int(input("Pick a number: "))
guesses_left -= 1

while guess != computer_number and guesses_left > 0:
    if guess < computer_number:
        print("Your guess is too low.")
    else:
        print("Your guess is too high.")

    print("you have", guesses_left, "guesses left")
    guess = int(input("Pick a number: "))
    guesses_left -= 1

if guess == computer_number:
    print("You got it right!")
else:
    print("Wrong! The number was", computer_number)


previous: and, or, not