-3

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?

Learner_15
  • 399
  • 2
  • 11

2 Answers2

2

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.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
-1

it looks like you are trying to convert string 'ten' to float 10.0 you cannot do that

your code is

sh = float(input("Enter Hours: "))

takes input in string format and then convert it in float value and then store it in a variable called sh

sr = float(input("Enter Rate: "))

this also do the same thing but insted of storing it to sh it store it to sr

the the try block starts it says do this if any error occur skip every thing and go to except block

    fh = float(sh)
    fr = float(sr) 

and because you cannot convert string to float you get an error in the try block and then go to except block.

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'>

this error come because you are trying to convert string to float in line 2 because input is 'ten' which is a string

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

this is working because you are not converting anything just taking input

and converit it on the try block which gives an error and then go to excpt block and print("Error, please enter numeric input")