首页 > 解决方案 > Python - 如何使用多变量重新输入异常?

问题描述

对python来说很新,我想知道如果用户输入负数,我如何让用户重新输入他们的多个变量而不让他们经历整个循环?这就是我到目前为止所拥有的。

while True:
    try:
        length = float(input("Length of the room in feet?\n").strip())
        if length < 0: raise Exception
        width = float(input("Width of the room in feet?\n").strip())
        if width < 0: raise Exception
        height = float(input("Height of the room in feet?\n").strip())
        if height < 0: raise Exception
        break
    except Exception:
        print("The number must be at least 0ft! Please try again.")
    except ValueError:
        print("Please print numerical values only! (grater than 0)")

因此,例如,如果他们正确输入了高度,但为宽度输入了负值,他们将不得不再次重新输入高度变量。通过为每个变量使用一个while循环来解决这个问题的唯一方法是什么?

标签: python-3.xexception

解决方案


也许您可以检查代码末尾的值并引发异常,如下所示

while True:
    try:
        length = float(input("Length of the room in feet?\n").strip())
        width = float(input("Width of the room in feet?\n").strip())
        height = float(input("Height of the room in feet?\n").strip())

        if (length < 0 or height < 0 or width < 0): 
            raise Exception
        else:
            break
    except Exception:
        print("The number must be at least 0ft! Please try again.")
    except ValueError:
        print("Please print numerical values only! (grater than 0)")

这段代码的作用是,它检查任何小于 0 的值,否则它再次要求所有三个变量值,这是你想要的吗?


推荐阅读