Guessing game
"""
guess.py
Guess a number. Give the user hits such as "too high" and "too low".
"""
import sys
import random
instructions = """\
I am thinking of an integer in the range 1 to 100 inclusive.
Try to guess it."""
print(instructions)
r = random.randint(1, 100) #an integer in the range 1 to 100 inclusive
while True:
print()
guess = input("Your guess: ")
guess = int(guess)
if guess > r:
print("Too high. Try again.")
elif guess < r:
print("Too low. Try again.")
else:
break
print("That's right!")
sys.exit(0)
I am thinking of an integer in the range 1 to 100 inclusive.
Try to guess it.
Your guess: 50
Too high. Try again.
Your guess: 25
Too high. Try again.
Your guess: 12
Too low. Try again.
Your guess: 18
Too high. Try again.
Your guess: 15
Too high. Try again.
Your guess: 14
That's right!
Things to try
-
Write the upper limit (100)
in only one place.
n = 100
instructions = f"""\
I am thinking of an integer in the range 1 to {n} inclusive.
Try to guess it."""
print(instructions)
n = random.randint(1, n) #an integer in the range 1 to n inclusive
-
Count how many times you went around the loop.
That's right! And it took you only 3 guesses!