Guess my Number |Python Game

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

Developers Group

--

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

import random

What is Python random() Function?

Python random() function generate random floating numbers between 0 and 1.

That is pretty simple. Now we can use it to generate a random number

number = random.randint(1, 10)

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

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

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!")

Download Full script from here

--

--

Developers Group

A Developer is responsible for coding, designing, deploying, and debugging development projects, typically on the server-side (or back-end).