As a beginner in Python, I wanted to build a simple yet engaging word guessing game. While implementing it, I encountered an issue where multiple success messages printed if the word was guessed correctly on the first try. I decided to refine my approach, enhance the game’s structure, and add practical features for a better user experience. This blog details my journey, the improvements made, and how the final code works.
The Issue
Initially, the program had separate conditions to check if the user guessed correctly, which led to duplicate success messages when the word was guessed right on the first attempt. Additionally, the code structure wasn’t optimal, requiring improvements in logic flow and readability.
The Improved Code
I resolved the issue by restructuring the code, incorporating a loop to handle all attempts, and ensuring an immediate program exit upon a correct guess.
import sys
secret_word = "tiger"
guess_limit = 3
print("Hello, welcome to the guessing game!")
print(f"Clue: It's an animal with {len(secret_word)} letters.")
for attempts in range(guess_limit):
remaining_attempts = guess_limit - attempts
# First attempt has a different prompt
if attempts == 0:
guess = input("Guess the secret word: ").strip().lower()
else:
guess = input(f"Wrong! {remaining_attempts} attempts left. Try again: ").strip().lower()
if guess == secret_word:
print("Congratulations! You've guessed it right!")
sys.exit() # Exit immediately after correct guess
print("\nSorry, you've run out of attempts!")
print(f"The secret word was '{secret_word.capitalize()}'.")
Key Improvements
Immediate Exit on Success
- Uses
sys.exit()
to terminate the program when the correct guess is made, preventing extra messages from printing.
Single Loop Structure
- Handles all guesses efficiently in a
for
loop, eliminating unnecessary conditions.
User-Friendly Features
Case-Insensitive Comparison
- Converts both the user input and secret word to lowercase, allowing variations in capitalization.
Displays Remaining Attempts
- Clearly informs the user how many guesses are left after each incorrect attempt.
Provides a Clue
- Hints at the number of letters in the secret word to make guessing easier.
Reveals the Secret Word on Failure
- Displays the correct answer if all attempts are exhausted, enhancing the learning experience.
Added Practical Functionality
Clue System
- Helps users by indicating the length of the word upfront.
Attempt Counter
- Provides real-time feedback on remaining guesses.
Input Sanitization
- Uses
.strip()
to prevent errors caused by accidental spaces before or after the word.
Cleaner Output Formatting
- Ensures better readability with clear messages and spacing.
How It Works
- The loop runs for
guess_limit
(3) attempts. - The first attempt prompt is different from subsequent ones, which display remaining tries.
- The input is converted to lowercase for a case-insensitive match.
- The program exits immediately with a success message if the guess is correct.
- If all attempts fail, the secret word is revealed.
How to Use
- Save the code as
word_guessing_game.py
. - Run it with Python 3.
- Test different cases (e.g., “TIGER”, “tiger”) to verify case insensitivity.
- Observe the attempt counter decreasing with each incorrect guess.
Final Thoughts
This improved structure prevents duplicate success messages and provides a polished gaming experience while maintaining clear and concise code. The enhancements make the game more interactive and user-friendly, setting a great foundation for future projects. If you’re just starting out in Python, this game is a fun way to practice loops, conditions, and user input handling!