如何使用Python 3编写一个不错的try / except组件,如果两个输入中的任何一个出现错误,它都会停止运行

问题描述 投票:0回答:1

大家!

我需要使用Python 3编写一个try / except组件,通过将工资率与工作时间相乘来计算总工资。输入必须为数字,否则将输出错误消息并停止。

hours = input("Enter Hours:")
try:
    hours = float(hours)
    rate = input("Enter Rate:") 
    try:
        rate = float(rate)
        if hours > 40:
            hours = hours - 40
            print("Pay:", 40*rate + hours*1.5*rate)
        else:
            print("Pay:", rate*hours)
    except:
        print("Error. Please enter numeric inputs.")
except:
     print("Error. Please enter numeric inputs.")

上面的代码只是在不提示任何内容的情况下继续运行(甚至没有第一行)。在第一个输入失败之后,下面仍然提示您输入第二个输入,整个过程应该停止。

    hours = input("Enter Hours:")
    try:
       hours = float(hours)
    except:
       print("Error. Please enter numeric inputs.")
    rate = input("Enter Rate:")
    try:
       rate = float(rate)
    if hours > 40:
       hours = hours - 40
       print("Pay:", 40*rate + hours*1.5*rate)
   else:
       print("Pay:", rate*hours)
   except:
       print("Error. Please enter numeric inputs.")

我是Python的新手,但我觉得有一个简单的解决方案。有人可以帮我吗?非常感谢!

python-3.x conditional-statements command-prompt try-except
1个回答
0
投票

一种可能的解决方案是编写一个帮助程序功能,该功能会继续提示用户,直到它读取可以转换为浮点值的字符串为止。

def read_float(prompt):

    while True:
        num = input(prompt)
        try:
            return float(num)
        except ValueError:
            print('Please input a numeric value.')

以及以下内容

hours = read_num("Enter Hours: ")
...
© www.soinside.com 2019 - 2024. All rights reserved.