Introduction: Want to quickly get started with Python? Today, we’ll play the ‘Guess the Number’ game with just 20 lines of code, easily mastering the core syntax! The complete code and advanced tips are included at the end, making it easy for beginners to understand!
1. Why Choose ‘Guess the Number’ as a Learning Case?
- 1. Concise and Effective: You only need to master four key concepts: random number generation, input/output, conditional statements, and loops to complete it.
- 2. Immediate Feedback: Run the code to interact, enhancing the sense of achievement in learning.
- 3. Strong Practicality: Covers user interaction, logical control, and other fundamental programming skills.
2. Step-by-Step Breakdown: A Hands-On Guide to Writing Code
Step 1: Import the Random Module
import random # Used for generating random numbers
- • Function:
<span>random</span>module provides functions to generate random numbers, ensuring each game has a different number.
Step 2: Generate the Target Number
target = random.randint(1, 100) # Generate a random integer between 1 and 100
- • Key Point:
<span>randint(a,b)</span>includes both endpoints, ensuring the range is correct.
Step 3: Receive User Input
guess = input("Please enter an integer between 1 and 100:") # Get user input
- • Note:
<span>input()</span>returns a string, which needs to be converted to a numeric type later.
Step 4: Core Logic – Conditional Statements and Loops
count = 0 # Record the number of guesses
while True: # Infinite loop until guessed correctly
guess = int(guess) # Convert to integer
count += 1
if guess < target:
print("Too low! Try again~")
elif guess > target:
print("Too high! Try again~")
else:
print(f"Congratulations! You guessed it right! It took you {count} tries.")
break # Exit the loop
- • Logic Analysis:
- • Loop Control:
<span>while True</span>continues running until<span>break</span>is triggered. - • Multiple Conditional Branches:
<span>if-elif-else</span>implements size comparison. - • Counting Functionality:
<span>count</span>records the number of attempts, enhancing the game’s engagement.
Step 5: Error Handling (Advanced Optimization)
try:
guess = int(guess)
except ValueError:
print("Please enter a valid number!")
continue # Skip this loop iteration and re-enter
- • Function: Prevents the program from crashing due to non-numeric input from the user.
3. Complete Code and Running Effect
import random
target = random.randint(1, 100)
count = 0
print("Welcome to the Guess the Number game! You have 10 chances between 1-100~")
while count < 10:
guess = input("Please enter your guess:")
try:
guess = int(guess)
except ValueError:
print("Please enter a valid number!")
continue
count += 1
if guess < target:
print("Too low!")
elif guess > target:
print("Too high!")
else:
print(f"🎉 Congratulations! You guessed it in {count} tries!")
break
else:
print(f"❌ Out of attempts! The correct answer was {target}.")
- • Effect Preview:
Welcome to the Guess the Number game! You have 10 chances between 1-100~ Please enter your guess: 50 Too low! Please enter your guess: 75 Too high! ...(final output)
4. Learning Outcomes and Further Thoughts
- 1. Core Knowledge Points:
- •
<span>random</span>module application - •
<span>while</span>loop and<span>break</span>control - •
<span>if-elif-else</span>multiple conditional judgments - • Exception handling (
<span>try-except</span>)
- • Add a scoring system (the more remaining attempts, the higher the score)
- • Record the history of guesses (e.g., “You guessed 50, 75”)
- • Use
<span>matplotlib</span><span> to plot a bar chart of the number of guesses (a first experience in data analysis)</span>
5. Frequently Asked Questions
❓ Q: Why do I always guess the wrong number?A: Check if you missed the<span>int(guess)</span><span> conversion or if your input is out of range.</span>
❓ Q: How can I make the game harder/easier?A: Modify the values in<span>randint(1,100)</span><span> or add hints (e.g., "The number is even").</span>
Conclusion: Learning programming starts with “writing your first program”! Copy the code into your Python environment and experience the joy of programming! If you like this article, feel free to share it with more programming beginners~ 💻✨