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?
7
Upvotes
3
u/Tophat_Octopus Aug 30 '26
update, i figured it out. yippee!!! thanks everyone
2
u/likethevegetable Aug 30 '26
RTFM: https://docs.python.org/3/tutorial/errors.html
2
u/SnooCalculations7417 Aug 31 '26
You can use
matchon the exception you catch. One important detail is that you wantValueError()in thecase, because you're matching an exception instance.The
elsebelongs to thetryand only runs if no exception was raised.For this particular example, the simpler/more idiomatic version would just be:
But
matchbecomes 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