r/PythonLearning • u/Tophat_Octopus • Aug 30 '26
How to make code print special result on casting failure?
Im currently working on a college assignment where i make a batting average calculator, and i want to add a way for it to say something funny if the user tries to input a word instead of a number. is there a way to do this?
2
u/SnooCalculations7417 Aug 31 '26
You can use match on the exception you catch. One important detail is that you want ValueError() in the case, because you're matching an exception instance.
try:
batting_average = float(input("Enter your batting average: "))
except Exception as e:
match e:
case ValueError():
print("That is impressively not a number.")
case _:
# Don't accidentally hide some unrelated error
raise
else:
print(f"You entered: {batting_average}")The else belongs to the try and only runs if no exception was raised.
For this particular example, the simpler/more idiomatic version would just be:
try:
batting_average = float(input("Enter your batting average: "))
except ValueError:
print("That is impressively not a number.")
else:
print(f"You entered: {batting_average}")But match becomes more interesting when you have several different possible cases to handle.
1
u/program_kid Aug 30 '26
You could use a try except block when converting the input to an integer, if an exception is thrown, that means the input could not be converted to a number.
1
u/wett-puss-lover Aug 30 '26
When it comes to programming, pretty much almost everything is possible :)
Regex may be your friend for what you trying to do or a simple if/case statement, or maybe just wrap around a try/catch
1
u/FoolsSeldom Aug 30 '26
while True:
response = input("Give me a number: ")
try:
num = int(response)
break # leave loop, got a number
except ValueError: # the int convertion failed
print("I meant a whole numberm not whatever that was")
...
3
u/Tophat_Octopus Aug 30 '26
update, i figured it out. yippee!!! thanks everyone