Number Guessing Game in Python

Let's Build a Number Guessing Game in Python


In this blog post, we'll walk through the creation of a simple yet engaging number guessing game using Python. This is a great project for beginners to learn about basic programming concepts like variables, loops, conditional statements, and user input.

The Game Logic

Our game will follow these rules:

  • The computer randomly selects a number within a specified range (let's say 1 to 10).
  • The player has a limited number of attempts to guess the number.
  • After each guess, the computer provides feedback:
    • "Guess Lower" if the guess is too high.
    • "Guess Higher" if the guess is too low.
    • "Congratulations, you guessed it!" if the guess is correct.

Let's Code

Here's the Python code that implements our game:

import random

print("Hello Humans")
print("""
1. Guess a number between 1 to 10
2. Game will for 3 attempts""")

machine_number = random.randint(1, 10)
# print (f"Machine Number: {machine_number}")  # For debugging
MAX_ATTEMPTS = 3

for attempt in range(MAX_ATTEMPTS):
    user_input = input(f"Round: {attempt} || Please enter your guess: ")
    # Check if the input is a valid number
    if user_input.isnumeric():
        user_number = int(user_input)
    else:
        print("Please enter a number")
        continue  # Skip to the next iteration

    if user_number == machine_number:
        print("Congrts, You guessed the correct number.")
        break  # Exit the loop if the guess is correct
    elif user_number > machine_number:
        print("Guess Lower")
    else:
        print("Guess Higher")

else:  # This block executes if the loop completes without a break
    print(f"Thank you for playing the game. \nThe Machine Number is: {machine_number}")
   
GitHub Link

Explanation

Import random: This line imports the random module, which provides functions for generating random numbers.

Initialization:
machine_number = random.randint(1, 10): Generates a random number between 1 and 10 and stores it in the machine_number variable.
MAX_ATTEMPTS = 3: Sets the maximum number of attempts the player has.

Game Loop

The for loop iterates MAX_ATTEMPTS times.

- user_input = input(...): Prompts the user to enter their guess and stores it in user_input.
Input Validation: Checks if user_input is a valid number using isnumeric(). If not, it prints an error message and continues to the next iteration using continue.
Comparison and Feedback: Compares user_number with machine_number and provides appropriate feedback ("Guess Lower," "Guess Higher," or "Congratulations").
Early Exit: If the guess is correct, the break statement exits the loop early.

End of Game

If the loop completes without a break (i.e., the player didn't guess correctly), it prints the machine_number and a thank-you message.

Further Improvements

  • User-defined Range: Allow the user to choose the range of numbers.
  • Scoring System: Track the number of attempts taken and provide a score.
  • Hints: Provide hints to the player (e.g., "The number is divisible by 2").
  • Graphical User Interface (GUI): Create a more visually appealing game using libraries like Tkinter or PyQt.

Conclusion

This simple number guessing game provides a foundation for understanding basic Python programming concepts. Feel free to experiment with the code and add your own creative twists!

If you have any questions or suggestions, please leave a comment below. Happy coding!

Comments