Hello World!
I decided that I would try putting my learning journey out there by creating a Github Repository and focusing on building and iterating over a Guessing Game developed with Python.
The reason for doing this is to reinforce my Python learning journey, and to starting building things (however small) instead of getting stuck in Tutorial Hell.
One thing I couldn't grasp, is how to capture errors, such as ValueError. Today, I did some reading, and decided to implement it into my simple game using Try-Except and ValueError as e. I did this so I could output the error in a print() statement.
Generate Random Number for Number to Guess:
# Generates a number from 1 - 10 inclusive
my_number = random.randint(1, 10)
This generates a number from 1 to 10 with 1 and 10 being inclusive.
Set Number of Guesses User has to guess the number:
# Set variable num_guesses to 3
num_guesses = 3
Currently, this is hard-coded to 3 guesses, but later I will try and make this a user-editable variable.
Definition for Guessing the Number and Handling Errors:
# I put the guess number functionality inside of a function so we can reuse it.
def guess_input():
try:
guess_number = int(input("Guess my Number (1 - 10): "))
# We are checking to see if the number input by the user is within range. If it is not, we are providing them with the error message below.
# I think there is an official way to do this, but for oour purposes, this is good enough.
if (guess_number > 10) or (guess_number < 1):
print(
"Invalid Input: Provided number is out of range. Please enter a number from 1 - 10"
)
# Except is catching all input which is not an Integer. Even a float.
# This is happening because we wrapped the input with int() to ensure that our input is an Integer.
# If it is anything other than an Integer, we are catching it with `ValueError`
except ValueError as e:
print(f"Ivalid Input: {e}. Please enter a number.")
return guess_number
I tested this out using characters other than an Integer such as a Float, 'A', '!', etc to ensure it works. I also just pressed enter to see how it handles not being given any sort of character.
I also wanted to ensure that a user can only enter in a value from 1 to 10.
The While Loop for the Game
while num_guesses > 0:
user_guess = guess_input()
if user_guess == my_number:
print(f"You guessed my number! It was {my_number}.")
break
else:
num_guesses -= 1 # This needs to go BEFORE the PRINT statement I do believe.
print(
f"That guess, {user_guess} is not my number.\nRemaining Guesses:{num_guesses}\nTry again!"
)
Top comments (0)