Python 3 - 过滤数字输入的问题



我试图控制输入只允许大于 0 的数字,但在测试此文本块时,如果我先输入非法字符(字符串、0 或负数),接收错误输出,然后输入有效值,它会返回我输入的第一个值而不是刚刚输入的有效值(然后导致我的脚本的其余部分由于类型不匹配或不合逻辑的值而失败)。我尝试移动"返回 x",但

无论哪种方式它都会做同样的事情。 在第二种情况下说"变量 X 在赋值前引用"。
def getPrice():
    try:
        x = float(input("What is the before-tax price of the item?n"))
        if x <= 0:
            print("Price cannot be less than or equal to zero.")
            getPrice()
        return x
    except ValueError:
        print("Price must be numeric.")
        getPrice()

def getPrice():
    try:
        x = float(input("What is the before-tax price of the item?n"))
        if x <= 0:
            print("Price cannot be less than or equal to zero.")
            getPrice()
    except ValueError:
        print("Price must be numeric.")
        getPrice()
    return x

我该如何解决这个问题?

另外,如果您好奇,这是针对学校作业的,我已经自己完成了整个程序,但我只是不知道如何调试它。

编辑:

我现在有一个工作方法:

def getPrice():
    while True:
        try:
            x = float(input("What is the before-tax price of the item?n"))
        except ValueError:
            print("Price must be numeric.")
            continue
        if x <= 0:
            print("Price cannot be less than or equal to zero.")
        else:
            return x
            break

并修复了原始代码块(但它仍然使用递归):

def getPrice():
        try:
            x = float(input("What is the before-tax price of the item?n"))
            if x <= 0:
                print("Price cannot be less than or equal to zero.")
                x = getPrice()
        except ValueError:
            print("Price must be numeric.")
            x = getPrice()
        return x

我不会拼出答案,因为它是家庭作业,但我会为你指出正确的方向。首先,我建议使用 while 循环而不是递归。

代码可能如下所示:

while True:
    try:
        x = <get input>
        if input is good:
            break
        else:
            <print error>
    except badstuff:
        <Print error>
        next #redundant in this case as we'd do this anyways

其次,你现在遇到的问题与变量作用域有关。当发生错误的输入时,您可以再次调用该函数,但不对输出执行任何操作。

请记住,第一个函数调用中的 x 与第二个函数调用中的 x 完全分开。

因此,如果你打算使用递归,你需要弄清楚如何传递x值"备份链"。

相关内容

最新更新