在Python中使用while循环时遇到问题

时间:2019-03-30 19:34:29

标签: python python-3.x loops

import sys
total = 0

while True:
    try:
        num = float(input("Enter a number: "))
        print(num, "has been added to the total")
        total += num
    except:
        print("This is not a number. Please re-enter")
        continue
    while True:
        again = input("Would you like to enter another number to add (Y or N)? ")
        if again == "Y" or "y":
            break     
        elif again == "N" or "n":
            print("The sum of the numbers is:", total)
            sys.exit()
        else:
            print("Invalid response. Please enter Y or N")

我的问题是在引入第二个while循环之后。似乎只在处理if again == "Y" or "y":,它将中断并返回我想要的第一个循环。但是,它不会处理其余条件。就像输入为“ N”或其他任何内容一样,它将中断并忽略我要设置的内容。非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您在使用此表达式时遇到了麻烦:

        if again == "Y" or "y":

运算符优先级的顺序表示它等同于此表达式:

        if (again == "Y") or ("y"):

第一项的值无关紧要,因为第二项不是None,所以它的值为True, 因此整个布尔表达式将始终计算True

您想要的是类似以下内容的东西:

        if again in {'Y', 'y'}:

正在测试集合成员资格。 记得也要调整'N'表达式。

或者,对于更高级别的问题,您可以选择其他方法:

        if again.lower() == 'y':