Why
I have been procrastinating on getting my first post up here. I have also been feeling a bit of imposter syndrome surrounding some of skills I have been learning and reinforcing over the past year. The solution I came up with is this:
- Going back and re-learning some of the basics
- Documenting the process here on this website
I was not sure what to do for this post, so I leaned on ChatGPT for a quick idea. I use this as a way to avoid my usual ‘analysis-paralysis’. I asked for a Python challenge that I could complete in an hour. It told me to make a guessing game. This post covers my thought process and what I came up with.
Step 1: Define the Goal
I needed to create a simple guessing game where the computer picks a random number, and the player has to guess it. I decided the game should give hints and repeat until the correct answer is found.
Step 2: Break Down the Goal
In order to make the goal more approachable, I tried to think the most logical process for this script to follow, this is what I got:
- Generate a random number and save it to a variable
- Ask a user for input and validate the input
- Create a loop that:
- Gets user input from the player
- Validates the user input
- Compares the guess to the random number
- Breaks the loop if guessed correctly
- Handle exceptions
Step 3: Write the Basic Functionality
Before I wrote a detailed version, I wrote a simple one where the program picks a number, asks the user to guess it, and prints these two numbers. This allowed me to confirm that the basic mechanics were working.
import random
def generate_random_number(range_max):
return random.randint(1, range_max)
range_max = 10
answer = generate_random_number(range_max)
guess = int(input(f"Guess a number between 1 and {range_max}: "))
print(f"You guessed: {guess}")
print(f"The answer was: {answer}")
Step 4: Add Some Validation
I quickly realized that entering a letter instead of a number caused the script return an error.
Guess a number between 1 and 10: a
Traceback (most recent call last):
File "C:\Users\home\Documents\GitHub\python-playground\test.py", line 8, in <module>
guess = int(input(f"Guess a number between 1 and {range_max}: "))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'a'
To fix this, I wrapped the line 8 input inside a try and except block to catch invalid inputs.
while True:
try:
guess = int(input(f"Guess a number between 1 and {range_max}: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
Next, I ensured the user’s guess was within the expected range by adding the is_valid_guess()
function.
def is_valid_guess(guess, range_max):
return 1 <= guess <= range_max
try:
guess = int(input(f"Guess a number between 1 and {range_max}: "))
if not is_valid_guess(guess, range_max):
print(f"Out of range! Please enter a number between 1 and {range_max}.")
break
except ValueError:
print("Invalid input. Please enter a number.")
Step 5: Polish and Test
Now I had to put it all together, I created the play_game()
function to hold my try and except block and call the other two functions. I also added did the following:
- Added basic text for context
- Created an attempts counter
- Created logic for guesses that are
- Too big
- Too small
- Just right (also displays total attempts)
Here it is.
import random
def generate_random_number(range_max):
return random.randint(1, range_max)
def is_valid_guess(guess, range_max):
return 1 <= guess <= range_max
def play_game():
range_max = 10
answer = generate_random_number(range_max)
attempts = 0
print("Welcome to the Python Guessing Game!")
print(f"Try to guess the number between 1 and {range_max}.")
while True:
try:
guess = int(input("Enter your guess: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue
if not is_valid_guess(guess, range_max):
print(f"Out of range! Please enter a number between 1 and {range_max}.")
continue
attempts += 1
if guess == answer:
print(f"Correct :) You guessed it in {attempts} attempts.")
break
elif guess < answer:
print("Too low, Try again.")
else:
print("Too high, Try again.")
if __name__ == "__main__":
play_game()
Breakdown of Each Function
- generate_random_number(range_max): Generates a random number between
1
andrange_max
. - is_valid_guess(guess, range_max): Checks if the user’s guess is within the allowed range.
- play_game(): Runs the game, handles user input, and gives feedback.
Gameplay
Welcome to the Python Guessing Game!
Try to guess the number between 1 and 10.
Enter your guess: 4
Too low! Try again.
Enter your guess: 6
Correct! You guessed it in 2 attempts.
Welcome to the Python Guessing Game!
Try to guess the number between 1 and 10.
Enter your guess: a
Invalid input. Please enter a number.
Enter your guess: 55
Out of range! Please enter a number between 1 and 10.
Enter your guess: 2
Too low! Try again.
Enter your guess: 5
Too low! Try again.
Enter your guess: 7
Too low! Try again.
Enter your guess: 9
Too low! Try again.
Enter your guess: 10
Correct! You guessed it in 5 attempts.
Final Thoughts
Looking back, this small project reinforced how important it is to break problems into smaller pieces. Even though this was a simple game, adding exception handling, user input validation, and structured functions helped create a more polished final product.
This process also reminded me that starting is often the hardest part. Even though it had been a while, once I started, ideas came naturally and I ended up enjoying the experience.
I hope to push myself with more challenging projects in future posts. I have been meaning to start working on a password manager for a while.
Until next post.
Ben