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.
import 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()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
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Generate Random Numbers in Python
Learn how to generate random numbers in Python. Compare randrange, randint, and uniform float generation with seeding control.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.