# Guess my Number | A Python Game

A number guessing game is very simple and easy to make, and we’ll only need a single library, random.
import random{codeBox}

What is Python random() Function?
Python random() function generate random floating numbers between 0 and 1.{alertInfo}

That is pretty simple. Now we can use it to generate a random number
number = random.randint(1, 10){codeBox}

This will generate a random integer between 1 and 10
We’ll also create a variable to hold how many guesses the player has to get the number correct.
guesses = 5{codeBox}

And then for the game, a while loop in which we will ask the user for their guess. Convert that guess into a number and check if it matches the number the computer generated.

If it does not, we can then check the number is higher or if it is lower, and let the user know.
while guesses != 0:
print("Guesses Left: " + str(guesses))
guess = int(input("Guess: "))

if guess == number:
print("Yay! You won!")
exit()
elif guess > number:
print("Guess is too high!")

elif guess < number:
print("Guess is too low!")

guesses -= 1{codeBox}

Finally outside of the loop.

We can add text to let the user know that they are out of guesses. Since the loop will only stop when guesses are equal to zero.
print("You ran out of guesses!"){codeBox}

Here’s what the completed script will look like.
import random

number = random.randint(1, 10)

guesses = 5

while guesses != 0:
print("Guesses Left: " + str(guesses))
guess = int(input("Guess: "))

if guess == number:
print("Yay! You won!")
exit()
elif guess > number:
print("Guess is too high!")

elif guess < number:
print("Guess is too low!")

guesses -= 1

print("You ran out of guesses!"){codeBox}

Subscribe our free newsletter for future projects & source code{alertWarning}

Stay updated with Developers Group official social media channels: