So as part of the exercises I was following from https://www.practicepython.org/ one of the exercises was to create a guessing game:
- Generate a random number
- Ask the user to guess the number and print
- Tell them whether they guessed to high or low
- Keep a track of how many guesses they had and tell them when the game ends.
This is the first exercise I’ve encountered where you need to be quite careful in how you structure your code. I’ll provide a breakdown of how I created mine.
### Generate a random number between 1 and 9. Ask the user to guess ### the number, then tell them whether they guessed too high or low. ### Extras: Keep the game going until the user types 'exit' and keep ### a track of how many guesses they've had. Tell them when the game ends. import random # Flag game as being in progress game = True # Initialise guess counter num_g = 0 # Generate random number r = random.randint(1,9) while game == True: g = input('Guess the number between 1 and 9 or type "exit" to quit the game: ') # Increment counter by 1 num_g = num_g + 1 # Add exit statement, if they don't want to exit, change their input to an integer. if g == 'exit': game = False break else: g = int(g) # If their guess matches random int, exit while loop if g == r: game = False elif g < r: print('You guessed too low') elif g > r: print('You guessed too high') if g == r: print('Congratulations you guessed the integer in',num_g,'guesses.') else: print('Game exited')
So we have quite a bit going on, as such I’ll break this down into sections:
First Section – Initialisation
This imports the ‘random’ module allowing us to generate a random integer later on down the line. Without doing so, we wouldn’t be able to have such an simple way of generating a random integer.
num_g = 0
This sets our guess counter to zero. This needs to be outside the while loop because otherwise, each time it goes through the loop, it would reset the number of guesses to zero.
game = True
This flags the game as being in progress and is used to continue the while loop. Once this is flagged as ‘False’ then the game will exit the while loop and continue on with the rest of the code.
Second Section – while Loop
As mentioned previously, we use the game = True to flag the game as being in session. Hence until that variable is changed (or we initiate a break) then we will iterate through the while loop endlessly.
g = input(' ... ')
This simply shows the user a message and asks for an input. A user can actually enter anything they like in here (e.g. a string, or a number > 9 or < 1). Without any error exceptions, the user won’t really know what they’ve done wrong.
num_g = num_g + 1
This part increases the number of guess by 1. For each time they iterate through the while loop, it adds one. This needs to be before the program resolves whether the guess is correct or not. If it was afterwards, they could guess correctly on their first go and it would show “correct in 0 guesses”. This could be avoided by initialising the variable num_g = 1. If we did choose to do that, the +1 increment would need to be after when the program resolves the guess.
if g == 'exit': break else: g = int(g)
This block needs to go before the resolution block. This is because the input of ‘exit’ is not an integer. If it was afterwards, the program would try and resolve whether ‘exit’ == r. (Where r is our random integer). Obviously it can’t resolve whether a str == int. As such, the program will throw an error.
By setting this before the resolution block, it will exit the game for the user or if they have actually entered an integer, it will convert this input to an int format.
After the ‘exit’ block, we have the resolution block where the program will compare the input against the random number generated at the very start of the game. This is simply a set of if and else if statements. Nothing fancy here.
Third Section – Final Lines
if g == r: print('Congratulations you guessed the integer in',num_g,'guesses.') else: print('Game exited')
Once the program has exited the while loop, it will check:
- Did it exit via a correct guess?
- Did it exit via a user command?
If it has exited via a correct guess then it will print the number of guesses. Otherwise it will simply state that the game has been exited.