Home Python Project Number Guessing Game using Python: A Fun Beginner Project

Number Guessing Game using Python: A Fun Beginner Project

by anupmaurya
3 minutes read
Number Guessing Game using Python: A Fun Beginner Project

Learning Python and looking for a fun, hands-on project? Look no further! Building a number guessing game is a fantastic way to solidify your understanding of basic programming concepts like variables, loops, conditional statements, and user input. Plus, it’s a great way to introduce others to the world of coding!

In this blog post, we’ll walk you through creating a simple number guessing game in Python.

The Game

The computer will generate a random number within a specified range (e.g., 1 to 100). The player has to guess the number. The computer will provide feedback, telling the player if their guess is too high or too low. The player continues guessing until they correctly identify the number.

The Code

import random

def number_guessing_game():
    print("Welcome to the Number Guessing Game!")
    print("I've chosen a secret number between 1 and 100.")

    secret_number = random.randint(1, 100)
    guesses_taken = 0

    while True:
        try:
            guess = int(input("Take a guess: "))
            guesses_taken += 1

            if guess < secret_number:
                print("Too low!")
            elif guess > secret_number:
                print("Too high!")
            else:
                print(f"Congratulations! You guessed the number in {guesses_taken} tries.")
                break
        except ValueError:
            print("Invalid input. Please enter a number.")

if __name__ == "__main__":
    number_guessing_game()

Explanation

  1. Import random: This line imports the random module, which allows us to generate random numbers.
  2. number_guessing_game() function: This function contains the core logic of the game.
  3. Welcome message: We print a welcome message to the player.
  4. secret_number generation: random.randint(1, 100) generates a random integer between 1 and 100 (inclusive) and stores it in the secret_number variable.
  5. guesses_taken variable: This variable keeps track of the number of guesses the player has made.
  6. while True loop: This loop continues indefinitely until the player guesses the correct number.
  7. try-except block: This handles potential errors if the player enters non-numeric input. The ValueError exception is caught if the user inputs something that can’t be converted to an integer.
  8. input() function: This prompts the player to enter their guess. int() converts the input to an integer.
  9. Conditional statements (if, elif, else): These statements compare the player’s guess to the secret_number and provide feedback.
  10. Winning condition: If the player’s guess matches the secret_number, the loop breaks, and a congratulatory message is printed.
  11. if __name__ == "__main__": block: This ensures that the number_guessing_game() function is called only when the script is executed directly (not when it’s imported as a module).

How to Run the Code

  1. Save the code as a Python file (e.g., guessing_game.py).
  2. Open a terminal or command prompt.
  3. Navigate to the directory where you saved the file.
  4. Run the script using the command: python guessing_game.py

Enhancements

  • Difficulty levels: You could introduce difficulty levels by changing the range of numbers.
  • Limited guesses: You could limit the number of guesses the player can take.
  • High score: You could store high scores in a file and display them to the player.
  • User interface: For a more polished experience, you could create a graphical user interface (GUI) using libraries like Tkinter or PyQt.

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.