【问题标题】:except, it returns the excepts but it continues to run, python [closed]除了,它返回异常但它继续运行,python [关闭]
【发布时间】:2017-09-28 01:23:12
【问题描述】:
hours = input("Enter hours: ")

rate = input("Enter rate: ")

try:
    hours = float(hours)
    rate = float(rate)
except:
    print("Enter real numbers")

def computepay(hours, rate):
    if hours <= 40.0:
        pay = hours * rate
        return pay
    elif hours > 40:
        pay = 40 * rate
        exhrs = (hours - 40) * (1.5 * rate)
        totpay = pay + exhrs
        return totpay

print("Pay: %s" % computepay(hours, rate))

【问题讨论】:

  • 继续运行是什么意思?

标签: python except


【解决方案1】:

except 块在try 块中的代码引发异常时执行。没有任何魔法可以知道您的用户需要重新输入这些数字,您必须自己提供代码。

此外,您应该始终明确您的例外情况。一种可能的方法是

while True:
    hours = input("Enter hours: ")
    rate = input("Enter rate: ")
    try:
        hours = float(hours)
        rate = float(rate)
        break              # end the while loop if no error occurred
    except ValueError:
        print("Enter real numbers")

【讨论】:

    【解决方案2】:

    这是正常行为。如果您出现一些异常,则脚本将被终止,在其他情况下,除了只会打印消息。 except 不会终止脚本。

    【讨论】:

      猜你喜欢
      • 2017-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 2023-02-06
      • 2021-06-20
      • 2017-11-20
      相关资源
      最近更新 更多