Guess my number - Python

Last edited: 24th June 2022

Can you create a 'Guess my number' game that generates a number then asks for user input before comparing the answers and giving a response?

Attempt to create your own version before using the code below because it will help you understand what is going on better. Your version will probably set the number manually rather than generating a random number. For a first attempt that would be okay because you are more likely to be able to understand what is happening which is what is important.

import random
correctanswer=False
number = random.randint(1,10)
print("I'm thinking of a number between 1 and 10")
while correctanswer==False:
    guess=input("Guess a number. ")
    guess=int(guess)
    if guess==number:
        print("Correct")
        correctanswer=True
    else:
        print("Wrong")
print("Congratulations! You win!")

Can you change the messages or the range of numbers? Can you count how many guesses someone has had?


This lesson is part of the Simple Python Challenges Course

Agree
We use cookies to provide you with a better service. Continue browsing if you are happy with this.