My First Python Game – Guess the Number

Sometimes the best way to get started with a new programming language is to do some reverse engineering. This consists of looking at an existing piece of code to find out how it works.

So let’s look at the piece of code for a fairly basic yet fully working Python game of “Guess the Number”. Look at the code. Look at the syntax. Try to understand what this code do, line by line. Tweak the code to see if you can adapt this game.

Here is the code.

import random

#Generate a Random Number between 0 and 100 and store it as 'numberToguess'


while userGuess!=numberToGuess:
    #Get the user to enter a number using the 'input' function and convert in to an Integer suing the 'int' function
    userGuess=int(input("Guess the number (between 1 and 100)"))
    #Compare this number, userGuess, with the numberToGuess - Display the right message if the userGuess is greater than, lower than or equal to the numberToGuess
    if userGuess>numberToGuess:
        print("Too high!")
    elif userGuess<numberToGuess:
        print("Too low!")
    elif userGuess==numberToGuess:
        print("Good guess, the number to guess was " + str(numberToGuess) + " indeed.")
        #End of game - exit the while loop

To see this code working use the following button. You will even be able to alter the code!


Your Challenge:

Could you change this code to count how many attempts you had at guessing the right number. Once you guess the correct number, the program should tell you how many guesses you used.



The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Did you like this challenge?

Click on a star to rate it!

Average rating 3.4 / 5. Vote count: 12

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!