【发布时间】:2021-07-10 07:18:01
【问题描述】:
我一直在试图弄清楚为什么 try-except 语句会起作用,但却卡在下面的代码上。
输入将是Enter Hours: 10 和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))
代码给了我一个Traceback,如下所示:
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'
但是,如果我将前 2 行更改为 ...
sh = input("Enter Hours: ")
sr = input("Enter Rate: ")
然后代码突然开始正常工作,结果如下:
Enter Hours: 10
Enter Rate: ten
Error, please enter numeric input
发生这种情况有什么解释?
【问题讨论】:
标签: python try-except