0

我想在不定义成功标准的情况下处理输入错误,即只循环用户输入结果不正确。我能找到的所有例子都需要一个成功的定义。

与其将所有可能的单位列为“成功”标准,我宁愿设置 else 函数来让用户回到开头并输入有效单位。

我有以下代码,它使用 pint(一个科学单元处理模块),如果用户输入无法识别的 hl_units,则会抛出错误。这只是将用户从程序中踢出错误并显示错误消息。如果可能的话,我希望用户被送回重新输入。

try:
    half_life = float(input("Enter the halflife of the nuclide: "))
    hl_units = input("Half-life units i.e. s, h, d, m, y etc: ")
    full_HL = C_(half_life, hl_units)
except:
    print("The half-life input is not recognised, maybe you entered incorrect units, please try again.")

else:

提前致谢。

4

1 回答 1

0

我会为此使用一个while循环:

input = False
while not input:
    try:
        half_life = float(input("Enter the halflife of the nuclide: "))
        hl_units = input("Half-life units i.e. s, h, d, m, y etc: ")
        full_HL = C_(half_life, hl_units)
        input = True
    except:
        print("The half-life input is not recognised, maybe you entered incorrect units, please try again.")
        input = False

我希望这对你有用:)

于 2020-04-17T19:05:39.233 回答