Number Guessing Game in Python

Creating a number-guessing game is a great way to familiarize yourself with Python basics. This tutorial will guide you through building a simple game in which the user has to guess a randomly selected number within a certain range.

How the Number Guessing Game Works

The Number Guessing Game is a simple Python console application where a player attempts to guess a randomly generated number within a specified range (e.g., 1 to 100) by following the game's prompts. Here's a breakdown of the game's workflow:

Initialization: When the game starts, it initializes by generating a random number within the specified range using Python's random.randint(min_value, max_value) function. This number is kept secret from the player.

User Interaction: The game then prompts the player to guess the secret number. The player inputs their guess through the console.

Guess Evaluation: The entered guess is evaluated against the secret number. There are three possible outcomes:
  • If the guess is lower than the secret number, the game responds with "Higher...", suggesting the player guess a higher number next time.
  • If the guess is higher than the secret number, the game responds with "Lower...", suggesting the player guess a lower number next time.
  • If the guess matches the secret number, the game congratulates the player, displaying the number of attempts it took to guess correctly.
Replay Option: After a game round ends (whether through a correct guess or otherwise), the player is prompted with the option to play again. If the player chooses to play again, the game restarts from step 1; otherwise, the game ends, thanking the player for playing.

Looping: The game can loop indefinitely, allowing for multiple rounds of play until the player decides to exit.

Step 1: Set Up Your Environment

Make sure you have Python installed on your computer. You can download it from python.org and follow the installation instructions for your operating system.

Step 2: Import Necessary Modules

Start your Python script by importing the random module, which will generate a random number for the user to guess.

import random

Step 3: Generate a Random Number

Define the range within which the random number should fall, and use random.randint to generate the number.

def get_random_number(min_value, max_value):
    return random.randint(min_value, max_value)

Step 4: Implement the Game Logic

Create a function to encapsulate the game's logic. This function prompts the user to guess the number, checks the guess, and provides feedback.

def guess_number(min_value, max_value):
    random_number = get_random_number(min_value, max_value)
    attempts = 0

    print(f"Guess the number between {min_value} and {max_value}!")

    while True:
        try:
            guess = int(input("Enter your guess: "))
            attempts += 1

            if guess < random_number:
                print("Higher...")
            elif guess > random_number:
                print("Lower...")
            else:
                print(f"Congratulations! You've guessed the number in {attempts} attempts.")
                break
        except ValueError:
            print("Please enter a valid integer.")

Step 5: Ask the User to Play Again

After a game finishes, you should offer the player a chance to play again. Add a function to ask this and return the player's choice.

def play_again():
    response = input("Do you want to play again? (yes/no): ").lower()
    return response == "yes"

Step 6: Main Game Loop

Finally, create a main function that starts the game and uses the play_again function to determine whether to start a new game after one ends.

def main():
    min_value = 1
    max_value = 100

    while True:
        guess_number(min_value, max_value)
        if not play_again():
            print("Thanks for playing!")
            break

Step 7: Run the Game

Add the Python execution guard to ensure the main function runs only when the script is executed directly (not when imported as a module).

if __name__ == "__main__":
    main()

Complete Code

Combine all the pieces above into your Python script. Here's how the complete game code looks:

import random

def get_random_number(min_value, max_value):
    return random.randint(min_value, max_value)

def guess_number(min_value, max_value):
    random_number = get_random_number(min_value, max_value)
    attempts = 0
    print(f"Guess the number between {min_value} and {max_value}!")

    while True:
        try:
            guess = int(input("Enter your guess: "))
            attempts += 1
            if guess < random_number:
                print("Higher...")
            elif guess > random_number:
                print("Lower...")
            else:
                print(f"Congratulations! You've guessed the number in {attempts} attempts.")
                break
        except ValueError:
            print("Please enter a valid integer.")

def play_again():
    response = input("Do you want to play again? (yes/no): ").lower()
    return response == "yes"

def main():
    min_value = 1
    max_value = 100
    while True:
        guess_number(min_value, max_value)
        if not play_again():
            print("Thanks for playing!")
            break

if __name__ == "__main__":
    main()


Running the Game

  • Save your script as something like number_guessing_game.py.
  • Open a terminal or command prompt.
  • Navigate to the directory where your script is saved.
  • Run the script using python number_guessing_game.py.
  • Follow the on-screen instructions to play the game.

Output

Guess the number between 1 and 100!
Enter your guess: 50
Higher...
Enter your guess: 60
Higher...
Enter your guess: 70
Higher...
Enter your guess: 80
Higher...
Enter your guess: 99
Lower...
Enter your guess: 90
Higher...
Enter your guess: 95
Lower...
Enter your guess: 92
Lower...
Enter your guess: 93
Lower...
Enter your guess: 98
Lower...
Enter your guess: 90
Higher...
Enter your guess: 97
Lower...
Enter your guess: 91
Congratulations! You've guessed the number in 13 attempts.
Do you want to play again? (yes/no): no
Thanks for playing!`

=== Code Execution Successful ===

Conclusion

Congratulations! You've just created a simple but fun number-guessing game in Python. This game introduces you to fundamental Python concepts such as loops, conditionals, input handling, and using standard modules like random. As you become more comfortable with Python, consider enhancing this game with features like difficulty levels, hints after certain attempts, or a graphical user interface using modules like Tkinter.

Comments