我希望有人解释一下这两者在解决这个问题方面有什么区别,以及哪一个更好。
使用 try 和 except 重写您的支付程序,以便您的程序通过打印消息并退出程序来优雅地处理非数字输入。下图展示了程序的两次执行:
Enter Hours: 20
Enter Rate : nine
Error, please enter numeric input
Enter Hours: forty
Error, please enter numeric input
input_hours = input('Enter Hours: ')
try:
hours = float(input_hours)
except ValueError:
print('Error, please enter numeric input')
quit()
input_rate = input('Enter Rate: ')
try:
rate = float(input_rate)
except ValueError:
print('Error, please enter numeric input')
quit()
if hours < 40:
pay = rate * hours
else:
overtime = hours - 40
pay = (rate * 40.0) + (1.5 * rate * overtime)
print(pay)
或者
try:
hrs = input('Enter Hours: ')
hr = float(hrs)
rate = input('Enter Rate: ')
rt = float(rate)
if float(hr) <= 40:
print(hr * rt)
else:
hrr = hr - 40
rr = hrr * 1.5 * rt
print(40 * rt + rr)
except:
print('Error, please enter numeric input')
叮当猫咪
米脂
大话西游666
相关分类