Exercise 4 - Guessing Games
Contents
Exercise 4 - Guessing Games¶
Andrew Valentine, Louis Moresi, louis.moresi@anu.edu.au
➤ Try playing this simple game.
import numpy as np
import sys
import os
sys.path.append(os.getcwd()+'/.hidden/')
import guessingGames as gg
gg.guessingGame(nmax=10)
I am thinking of a number between 1 and 10
Make a guess:1
Sorry, try again.
Make a guess:4
Sorry, try again.
➤ Can you write your own version?
A couple of hints to help you:
To read input from the keyboard, you can use
x = input(message)
where message
is the prompt shown to the user (e.g. ‘Make a guess:’ in gg.guessingGame
). Whatever the user types in gets stored in the variable x
. Note that x
contains a string of characters, even if the user types in a number. You can use int(x)
to convert the input to an integer (and float(x)
if you want to convert it to a floating-point number).
To generate a random integer, you can call the function
np.random.randint(lo,hi)
wherelo
is the smallest integer you want to generate, andhi
is one greater than the largest integer.
# Try it here!
What happens if the user types something in that isn’t an integer? Can you make your version robust?¶
➤ Here’s another one to play:
gg.higherOrLower(nmax=100)
➤ Try writing your own version.
You should be able to use the code you wrote for guessingGame
as a starting point.
# Try it here!
➤ Here’s a final one to try.
gg.montyHall(3)
➤ Can you make your own version?
# Try it here!