在没有定义正确答案的情况下处理错误

Dealing with an error without defining what the correct answer is

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

与其列出所有可能的单位作为 "success" 条件,我宁愿设置 else 函数将用户返回到开头并输入有效单位。

我有以下使用 pint(科学单位处理模块)的代码,如果用户输入无法识别的 hl_units,它会抛出错误。这只是将用户踢出错误的程序,并显示有关出错的消息。如果可能,我希望将用户送回 re-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)
except:
    print("The half-life input is not recognised, maybe you entered incorrect units, please try again.")

else:

提前致谢。

我会为此使用 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

我希望这对你有用:)