Here is the code for the “Number Guessing Game” mini-project. It combines a while loop, the break statement, and basic if-elif-else conditions.
Python
import random
print("Welcome to The Number Guessing Game!")
print("I have picked a random number between 1 and 50.")
# The computer picks a random number between 1 and 50
secret_number = random.randint(1, 50)
# Keep track of how many guesses the player makes
attempts = 0
# Start an infinite loop that allows continuous guessing
while True:
try:
# Ask the player for their guess
guess = int(input("Enter your guess: "))
attempts += 1
# Give hints based on the guess
if guess < secret_number:
print("Higher! Try again.")
elif guess > secret_number:
print("Lower! Try again.")
else:
# The guess matches the secret number
print(f"Congratulations! You guessed the number {secret_number} correctly!")
print(f"It took you {attempts} attempts.")
break # Exit the loop since the game is won
except ValueError:
# Handles the error if the user types a letter instead of a number
print("Invalid input. Please enter a whole number.")
How It Works:
import random: This brings in Python’s built-in random module so the computer can userandom.randint(1, 50)to generate the secret number.while True:: This creates an infinite loop. The game will keep asking for guesses over and over again until it is explicitly told to stop.try...except ValueError: This ensures the program doesn’t crash if the player accidentally types a letter (like “A”) instead of a number.if/elif/else: This compares the player’s guess to the secret number and provides the “higher” or “lower” feedback.break: Once the player’s guess equals the secret number, theelseblock runs, prints the victory message, and hits thebreakstatement to terminate the game loop.