Python Number Guessing Game
A classic beginner Python project. Build an interactive number guessing game that uses random generation, while loops, and user input validation.
How it Works
Games are a fantastic way to learn programming logic and flow control.
This script generates a random number between 1 and 100, then traps the user in a "while" loop until they guess the correct number.
It provides hints (too high, too low) by checking the state of their guess against the target.
Source Code
Interactive number guessing loop utilizing standard built-in libraries.
guessing_game.py
Try in Editorimport random
def play_game():
target = random.randint(1, 100)
attempts = 0
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
# Simulating a session (since input() blocks in standard runs, we mock it for the demo)
mock_guesses = [50, 75, 60, 65, target]
for guess in mock_guesses:
attempts += 1
print(f"\nYour guess: {guess}")
if guess < target:
print("Too low!")
elif guess > target:
print("Too high!")
else:
print(f"Congratulations! You guessed it in {attempts} attempts!")
break
play_game()Terminal Output
Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.
Your guess: 50
Too low!
Your guess: 75
Too high!
Your guess: 60
Too low!
Your guess: ... (game continues)Real-world Applications
- Understanding state tracking across while loops
- Handling interactive I/O streams safely
- Logic gate implementation
Frequently Asked Questions
How do I use actual user input?
Replace the mock array loop with `guess = int(input("Enter your guess: "))` inside a `while True:` loop.
More Examples
Python Random Password Generator
Generate secure, random passwords in Python. Learn to use the random module alongside string constants to build robust security tools.Python Simple Calculator Script
Build a basic calculator in Python. Learn how to map mathematical operators, take user execution flows, and handle logic natively.