【问题标题】:Issues with 'x is None', python 3.x'x is None'的问题,python 3.x
【发布时间】:2018-03-03 07:58:27
【问题描述】:

所以,我正在尝试创建一个计算器,您可以在其中将数字输入控制台,直到您按 Enter 键而不输入任何数字。

num1 = 0
num2 = 0
    if addec == ("Go"):
        adloop = 1
            print(para1, """ To exit,
press enter with no number

Please input the first number""", para1)
            sleep(1.5)
            num1 = float(input("--> "))

    while adloop == 1:
        try:
            num1 = num1 + num2
            print("Insert Number")
            num2 = float(input("--> "))

        except:
            if num2 is None:
                print("The answer is", num1)
            else:
                print(para1, """  ERROR: Invalid Response.

Please start again""")

错误在于,即使 num2 为空,程序也会跳过“else”语句并在重新启动之前运行 ERROR 行,而不会返回答案。
(代码只是一小段摘录,所以如果有任何遗漏,可能是在其他地方)

谢谢,

【问题讨论】:

  • 你的缩进也错误
  • num2 永远不会失去它的价值。在请求input之前将其重置为None
  • 在该程序中,num2永远从未设置为None
  • @Jean-FrançoisFabre 谢谢,这似乎已经解决了

标签: python python-3.x null


【解决方案1】:

除了num2 永远不会设置为None 之外,没有代码可以实际退出循环(成功或失败)。此外,代码中的某些元素在示例方面是死胡同(例如@987654323 @、para1sleep(1.5)、多行字符串等)在展示您想提出问题的可运行示例时,您应该清除它们:

print("To exit, press enter with no number.")
print("Please input the first number:")
num1 = float(input("--> "))

num2 = 0

while True:
    try:
        num1 = num1 + num2
        num2 = None
        print("Insert Number")
        num2 = float(input("--> "))
    except ValueError:
        if num2 is None:
            print("The answer is", num1)
            break
        else:
            exit("ERROR: Invalid Response.  Please start again")

我们也可以把它翻过来,这样我们也可以捕捉到 num1 的错误值:

print("To exit, press enter with no number.")
print("Please input the first number:")

num2 = 0

try:
    num1 = float(input("--> "))

    while True:
        num1 = num1 + num2
        num2 = None
        print("Insert Number")
        num2 = float(input("--> "))
except ValueError:
    if num2 is None:
        print("The answer is", num1)
    else:
        exit("ERROR: Invalid Response.  Please start again")

用法

% python3 test.py
To exit, press enter with no number.
Please input the first number:
--> goat
ERROR: Invalid Response.  Please start again
%

【讨论】:

    猜你喜欢
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    相关资源
    最近更新 更多