How do you make a Number Guessing Game in Python?

December 8, 2022 Off By Zak Morris

Welcome to this tutorial on how to make a Python Guessing Number Game! This game will challenge the user to guess a randomly generated number between 1 and 10. If the user guesses the correct number, they win, otherwise they will be prompted to try again until they either guess the correct number or run out of attempts.

First, let’s import the necessary modules. We will be using the random module to generate a random number and the sys module to exit the program if the user runs out of attempts.

Python
import random
import sys


Next, we need to generate a random number between 1 and 100. We can do this using the randint() method from the random module.

Python
random_number = random.randint(1, 100)


Now, we need to set up the number of attempts the user has to guess the correct number. Let’s set this to 10 for now.

Python
attempts = 10


Next, we need to create a while loop that will continue until the user either guesses the correct number or runs out of attempts. Inside the while loop, we will prompt the user to enter a number and check if it matches the random number. If the user guesses correctly, we will print a congratulations message and exit the program using the sys.exit() method. If the user does not guess correctly, we will decrement the number of attempts by 1 and prompt the user to try again.

Python
while attempts > 0:
user_guess = int(input("Enter a number between 1 and 100: "))
if user_guess == random_number:
print("Congratulations! You guessed the correct number.")
sys.exit()
else:
attempts -= 1
print("Incorrect guess. You have {} attempts remaining.".format(attempts))


Finally, outside of the while loop, we will print a message if the user runs out of attempts and exit the program.

Python
print("You have run out of attempts. Better luck next time.")
sys.exit()


And that’s it! We have created a Python Guessing Number Game that will challenge the user to guess a randomly generated number between 1 and 100. The user will have 10 attempts to guess the correct number, and if they run out of attempts, the program will exit.

Here is the complete code:

Python
import random
import sys

random_number = random.randint(1, 100)
attempts = 10

while attempts > 0:
user_guess = int(input("Enter a number between 1 and 100: "))
if user_guess == random_number:
print("Congratulations! You guessed the correct number.")
sys.exit()
else:
attempts -= 1
print("Incorrect guess. You have {} attempts remaining.".format(attempts))

print("You have run out of attempts. Better luck next time.")
sys.exit()


Try running this code and see if you can guess the correct number!