Search code examples
pythontry-except

Why does the try-except not work when the variable input is given as a float?


I've been trying to work out why how the try-except statement works out but became stuck on the following code.

The input will be Enter Hours: 10 and Enter Rate: ten

sh = float(input("Enter Hours: "))
sr = float(input("Enter Rate: "))
try:
    fh = float(sh)
    fr = float(sr)  # string rate
except:
    print("Error, please enter numeric input")
    quit()
print(fh, fr, sep='')
sp = fh * fr
print("Pay: ", round(sp, 2))

The code gives me a Traceback as the following:

Traceback (most recent call last):
  File "C:\Users~~~~", line 2, in <module>
    sr = float(input("Enter Rate: "))
ValueError: could not convert string to float: 'ten'

However, if I change the first 2 lines to ...

sh = input("Enter Hours: ")
sr = input("Enter Rate: ")

Then the code suddenly starts to work properly resulting as the following:

Enter Hours: 10
Enter Rate: ten
Error, please enter numeric input

What explanation is there for this to happen?


Solution

  • In the original code snippet, you attempt to cast the user input to float immediately, i.e. outside the try block. This throws a ValueError (as expected) but since it does so before the try, it cannot be caught and handled as you expect.