How to Create a Python Guessing Game?

Estimated read time 2 min read

Here’s an example of a simple Python guessing game:

import random

# Generate a random number between 1 and 100
number = random.randint(1, 100)

# Initialize the number of guesses
num_guesses = 0

# Loop until the player guesses the correct number
while True:
    # Prompt the player to enter a guess
    guess = int(input("Guess a number between 1 and 100: "))
    
    # Increment the number of guesses
    num_guesses += 1
    
    # Check if the guess is correct
    if guess == number:
        print("Congratulations, you guessed the number in", num_guesses, "guesses!")
        break
    elif guess < number:
        print("Too low, try again.")
    else:
        print("Too high, try again.")

In this guessing game, the player is prompted to guess a number between 1 and 100. The program generates a random number between 1 and 100 using the random.randint() function.

The player’s guess is compared to the random number, and the program provides feedback on whether the guess is too high or too low. If the player guesses the correct number, the program congratulates the player and displays the number of guesses it took to guess the number.

The while loop continues until the player guesses the correct number. The break statement is used to exit the loop and end the game.

Note that this is just a simple example, and you can modify the game to suit your needs. For example, you could add a limit on the number of guesses the player is allowed to make, or you could add additional features such as a scoring system or a leaderboard.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply