python workout: exercise 1
number guessing game
problem
For this exercise
- Write a function (
guessing_game) that takes no arguments.- When run, the function chooses a random integer between 0 and 100 (inclusive).
- Then ask the user to guess what number has been chosen.
- Each time the user enters a guess, the program indicates one of the following:
- Too high
- Too low
- Just right
- If the user guesses correctly, the program exits. Otherwise, the user is asked to try again.
- The program only exits after the user guesses correctly.
attempts
This should hopefully be a straightforward function:
import random
def guessing_game() -> None:
number = random.randint(0,100)
guess = None
while guess != number:
guess = int(input('Guess the number: '))
if guess > number:
print('Too high')
if guess < number:
print('Too low')
print('Just right')
We just need to output the right messages to pass the tests though:
import random
def guessing_game() -> None:
number = random.randint(0,100)
guess = None
while guess != number:
guess = int(input('Guess the number: '))
if guess > number:
print(f'Your guess of {guess} is too high!')
if guess < number:
print(f'Your guess of {guess} is too low!')
print(f'Right! The answer is {number}')
solution
The author uses the infinite loop (i.e. while True) approach:
def guessing_game():
"""Generate a random integer from 1 to 100.
Ask the user repeatedly to guess the number.
Until they guess correctly, tell them to guess higher or lower.
"""
answer = random.randint(0, 100)
while True:
user_guess = int(input('What is your guess? '))
if user_guess == answer:
print(f'Right! The answer is {user_guess}')
break
if user_guess < answer:
print(f'Your guess of {user_guess} is too low!')
else:
print(f'Your guess of {user_guess} is too high!')
beyond the exercise
only 3 tries
-
problem
Modify this program, such that it gives the user only three chances to guess the correct number. If they try three times without success, the program tells them that they didn’t guess in time and then exits.
-
attempts
We can extend the author’s solution as follows:
def guessing_game(): """Generate a random integer from 1 to 100. Ask the user repeatedly to guess the number. Until they guess correctly, tell them to guess higher or lower. """ answer = random.randint(0, 100) tries = 0 while True: if tries == 3: print(f"You didn't get it right in time...") break user_guess = int(input('What is your guess? ')) tries += 1 if user_guess == answer: print(f'Right! The answer is {user_guess}') break if user_guess < answer: print(f'Your guess of {user_guess} is too low!') else: print(f'Your guess of {user_guess} is too high!')
random number bases
-
problem
Not only should you choose a random number, but you should also choose a random number base, from 2 to 16, in which the user should submit their input. If the user inputs “10” as their guess, you’ll need to interpret it in the correct number base; “10” might mean 10 (decimal), or 2 (binary), or 16 (hexadecimal).
-
attempts
Let’s only select from 3 possible bases referenced in the problem: 2, 10, and 16.
And let’s just use
randomto select from a list of these bases.def guessing_game(): """Generate a random integer from 1 to 100. Ask the user repeatedly to guess the number. Until they guess correctly, tell them to guess higher or lower. """ base = random.choice([2,10,16]) answer = random.randint(0, 100) print(f'The number is in base {base}') while True: user_guess = int(input('What is your guess? '), base) if user_guess == answer: print(f'Right! The answer is {user_guess}') break if user_guess < answer: print(f'Your guess of {user_guess} is too low!') else: print(f'Your guess of {user_guess} is too high!')The only downside of this approach is that it prints the
user_guessin base 10 instead of the original base.But there doesn’t seem to be a nice way to do this in Python’s stdlib aside from maybe some string formatting workarounds.
from a dictionary
-
problem
Try the same thing, but have the program choose a random word from the dic- tionary, and then ask the user to guess the word. (You might want to limit your- self to words containing two to five letters, to avoid making it too horribly difficult.) Instead of telling the user that they should guess a smaller or larger number, have them choose an earlier or later word in the dict.
-
attempts
The only way to do this would be to have a dictionary dataset.
Or PyDictionary. But this seems to be a Python 2 package…
So let’s just use a test dictionary of 5 words. This implementation should be rather straightforward anyways. Especially since we can reuse the matching logic (i.e. operators like
<) to compare word strings:def word_guessing_game(): dictionary = ['apple', 'bee', 'cat', 'dove', 'eagle', 'fox', 'gator'] answer = random.choice(dictionary) while True: user_guess = input('What is your guess? ') if user_guess == answer: print(f'Right! The answer is {user_guess}') break if user_guess < answer: print(f'Your guess of {user_guess} is too low!') else: print(f'Your guess of {user_guess} is too high!')