🕯️ Magic Note
The number guessing game is not just a toy. It demonstrates core programming patterns: the game loop (while True with break), input validation, state tracking (number of attempts, secret number), and clean separation of concerns (different functions for different tasks). Master this project, and you master a pattern that can be extended to many other games.
Python
import random
# Random number between 1 and 100 (inclusive)
secret_number = random.randint(1, 100)
# For testing (remove in final game)
# print(f”Secret number is: {secret_number}”)
Python
guess = int(input(“Enter your guess (1-100): “))
Python
if guess < secret_number:
print(“Too low! Try a higher number.”)
elif guess > secret_number:
print(“Too high! Try a lower number.”)
else:
print(“Correct! You got it!”)
Python
import random
secret_number = random.randint(1, 100)
attempts = 0
print(“Welcome to the Number Guessing Game!”)
print(“I am thinking of a number between 1 and 100.”)
while True:
guess = int(input(“Enter your guess: “))
attempts += 1
if guess < secret_number:
print(“Too low!”)
elif guess > secret_number:
print(“Too high!”)
else:
print(f”Correct! You guessed it in {attempts} attempts!”)
break
🕯️ Magic Note
The while True loop runs forever. The break only executes when the guess is correct. This is the standard pattern for a game loop.
Python
import random
secret_number = random.randint(1, 100)
attempts = 0
print(“Welcome to the Number Guessing Game!”)
print(“I am thinking of a number between 1 and 100.”)
while True:
try:
guess = int(input(“Enter your guess (1-100): “))
if guess < 1 or guess > 100:
print(“Please enter a number between 1 and 100.”)
continue
attempts += 1
if guess < secret_number:
print(“Too low!”)
elif guess > secret_number:
print(“Too high!”)
else:
print(f”Correct! You guessed it in {attempts} attempts!”)
break
except ValueError:
print(“Invalid input. Please enter a number.”)
Python
import random
def get_random_number(low, high):
“””Return a random integer between low and high (inclusive).”””
return random.randint(low, high)
def get_player_guess():
“””Get a valid guess from the player.”””
while True:
try:
guess = int(input(“Enter your guess (1-100): “))
if 1 <= guess <= 100:
return guess
print(“Please enter a number between 1 and 100.”)
except ValueError:
print(“Invalid input. Please enter a number.”)
def check_guess(guess, secret):
“””Compare guess with secret and return a tuple (is_correct, message).”””
if guess < secret:
return False, “Too low!”
elif guess > secret:
return False, “Too high!”
else:
return True, “Correct!”
def play_game():
“””Main game function.”””
print(“=” * 40)
print(“Welcome to the Number Guessing Game!”)
print(“I am thinking of a number between 1 and 100.”)
secret_number = get_random_number(1, 100)
attempts = 0
while True:
guess = get_player_guess()
attempts += 1
is_correct, message = check_guess(guess, secret_number)
print(message)
if is_correct:
print(f”You won in {attempts} attempts!”)
break
# Run the game
if __name__ == “__main__”:
play_game()
🕯️ Magic Note
The if __name__ == “__main__” guard allows this file to be imported without running the game automatically. It only runs when you execute the script directly.
Python
import random
def choose_difficulty():
“””Let player choose difficulty and return (range_max, max_attempts).”””
print(“\nChoose difficulty:”)
print(“1. Easy (1-50, 10 attempts)”)
print(“2. Medium (1-100, 7 attempts)”)
print(“3. Hard (1-200, 5 attempts)”)
while True:
choice = input(“Enter 1, 2, or 3: “)
if choice == “1”:
return 50, 10
elif choice == “2”:
return 100, 7
elif choice == “3”:
return 200, 5
else:
print(“Invalid choice. Please enter 1, 2, or 3.”)
def play_game_with_difficulty():
range_max, max_attempts = choose_difficulty()
secret_number = random.randint(1, range_max)
attempts = 0
print(f”\nI am thinking of a number between 1 and {range_max}.”)
print(f”You have {max_attempts} attempts.”)
while attempts < max_attempts:
try:
guess = int(input(f”\nAttempt {attempts + 1}/{max_attempts}: “))
if guess < 1 or guess > range_max:
print(f”Please enter a number between 1 and {range_max}.”)
continue
attempts += 1
if guess < secret_number:
print(“Too low!”)
elif guess > secret_number:
print(“Too high!”)
else:
print(f”\nCorrect! You guessed it in {attempts} attempts!”)
return
except ValueError:
print(“Invalid input. Please enter a number.”)
print(f”\nOut of attempts! The number was {secret_number}.”)
print(“Better luck next time!”)
Python
def ask_replay():
“””Ask player if they want to play again.”””
while True:
answer = input(“\nDo you want to play again? (yes/no): “).lower()
if answer in [“yes”, “y”]:
return True
elif answer in [“no”, “n”]:
return False
else:
print(“Please enter yes or no.”)
def main():
“””Main program loop with replay option.”””
print(“Welcome to the Number Guessing Game!”)
while True:
play_game_with_difficulty()
if not ask_replay():
print(“\nThanks for playing! Goodbye!”)
break
if __name__ == “__main__”:
main()
Python
import random
def get_random_number(low, high):
“””Return a random integer between low and high (inclusive).”””
return random.randint(low, high)
def choose_difficulty():
“””Let player choose difficulty.”””
print(“\n” + “=” * 40)
print(“Choose Difficulty:”)
print(“1. Easy – Numbers 1-50, 10 attempts”)
print(“2. Medium – Numbers 1-100, 7 attempts”)
print(“3. Hard – Numbers 1-200, 5 attempts”)
print(“=” * 40)
while True:
choice = input(“Enter 1, 2, or 3: “)
if choice == “1”:
return 50, 10
elif choice == “2”:
return 100, 7
elif choice == “3”:
return 200, 5
else:
print(“Invalid choice. Please enter 1, 2, or 3.”)
def get_player_guess(range_max, attempts_used, max_attempts):
“””Get and validate player guess.”””
while True:
try:
guess = int(input(f”Attempt {attempts_used + 1}/{max_attempts}: “))
if 1 <= guess <= range_max:
return guess
print(f”Please enter a number between 1 and {range_max}.”)
except ValueError:
print(“Invalid input. Please enter a number.”)
def check_guess(guess, secret):
“””Compare guess with secret number.”””
if guess < secret:
return False, “📉 Too low!”
elif guess > secret:
return False, “📈 Too high!”
else:
return True, “🎉 Correct!”
def play_round():
“””Play one round of the game.”””
range_max, max_attempts = choose_difficulty()
secret = get_random_number(1, range_max)
attempts_used = 0
print(f”\nI am thinking of a number between 1 and {range_max}.”)
print(f”You have {max_attempts} attempts to guess it.\n”)
while attempts_used < max_attempts:
guess = get_player_guess(range_max, attempts_used, max_attempts)
attempts_used += 1
is_correct, message = check_guess(guess, secret)
print(message)
if is_correct:
print(f”✨ You won in {attempts_used} attempts! ✨”)
return True
print(f”\n💀 Out of attempts! The number was {secret}. 💀”)
return False
def ask_replay():
“””Ask player if they want to play again.”””
while True:
answer = input(“\nPlay again? (yes/no): “).lower().strip()
if answer in [“yes”, “y”]:
return True
elif answer in [“no”, “n”]:
return False
else:
print(“Please enter yes or no.”)
def main():
“””Main game loop.”””
print(“=” * 50)
print(“🎲 Welcome to the Number Guessing Game! 🎲”)
print(“=” * 50)
wins = 0
games = 0
while True:
result = play_round()
games += 1
if result:
wins += 1
print(f”\n📊 Score: {wins} wins out of {games} games”)
if not ask_replay():
print(“\n🌟 Thanks for playing! Goodbye! 🌟”)
break
if __name__ == “__main__”:
main()
- Add a hint system (every 3 attempts, give a hint like “number is even/odd”)
- Add a high score system (lowest attempts in each difficulty)
- Add a guessing range display (show the possible range based on previous guesses)
- Add difficulty “Custom” where player sets the range and attempts
- Add a timer to see how fast the player guesses
- Save statistics to a file so they persist between sessions
- Forgetting to convert user input to the correct type
- Not validating user input (crashes on invalid input)
- Infinite loops without a proper exit condition
- Modifying the secret number inside the loop
- Not resetting variables between games
- Code that is too much inside the loop (should be organized into functions)
- What module do you use to generate random numbers?
- How do you prevent the game from crashing if the user enters text instead of a number?
- What is the purpose of the continue statement in the game loop?
- Why do we use functions to organize the game code?
- How would you add a high score feature?
⚡ Whisper
You have built a game. Not just a script that runs once. A real game with difficulty levels, replayability, and user input validation. This is not a toy project. This is a pattern. The game loop. The input loop. The validation pattern. The replay pattern. You will see these patterns again and again. In web servers waiting for requests. In chatbots waiting for messages. In GUI applications waiting for clicks. The structure is always the same: initialize, loop, process input, provide output, check exit condition, repeat. You have learned this structure by building a game. Now you can build anything. A number guessing game is small. But the patterns inside it are the same patterns that power Instagram, Spotify, and Google. You have taken a step from writing code to building systems. Congratulations. Now go play your game. Then add another feature. Then build something new. The path is open. Walk it.