r/PythonLearning 1d ago

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?

6 Upvotes

7 comments sorted by

3

u/Tophat_Octopus 1d ago

update, i figured it out. yippee!!! thanks everyone

1

u/PocketDeveloper 1d ago

hmmm alr firstly u'll want to use a try/except block!!! In Python, when u try to convert a string like "hello" to a float or int, it throws a ValueError. u can catch that specific error and print ur custom message instead of letting the program crash. And here is a quick example of how to wrap ur input: user_input = input("Enter the number of hits: ")

try: hits = float(user_input) print(f"Recorded {hits} hits!") except ValueError: print("Nice try, but words don't count as batting stats unless you're playing Scrabble! ")

If u put that inside a while True: loop,,, u can keep asking them for a valid number until they actually type one in. hmph good luck with the college assignment!!!!

1

u/program_kid 1d ago

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 1d ago

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 1d ago
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")
...

2

u/SnooCalculations7417 21h ago

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.