while语句后的Else语句,以及字符串列表的字符串比较?

时间:2017-01-12 11:29:21

标签: python if-statement while-loop conditional

我正在尝试创建一个小的测试脚本,将某些内容添加到注释中。下面包含的是我将在脚本中执行的主要功能。问题似乎是当else块的计算结果为false时,我无法运行while块(也就是说,当它评估为不是这四个块中的任何一个时)选项),while块只是在无限循环中继续。我还尝试在while循环中插入break,但这会在while循环执行后终止脚本。

当评估为false时,如何从while移动到else块?为什么我现在的工作方式不能像我希望的那样工作呢?感谢。

def start():
    q01 = input("What is the subject of your note?\n")
    q02 = input("Are you certain that the subject of your note is " + q01 + "?\n")
    while q02 == 'No' or 'no' or 'NO' or 'n':
       q01 = input("So, what is the subject of your note?\n")
       q02 = input("Are you certain now that the subject of your note is " + q01 + "?\n")
    else:
       q03 = Enter("Enter the content of your note")

4 个答案:

答案 0 :(得分:3)

你的罪魁祸首是while循环条件:

while q02 == 'No' or 'no' or 'NO' or 'n':

这相当于:

while (q02 == 'No') or 'no' or 'NO' or 'n':

作为'no''NO''n'都是非空字符串,它们评估为True,因此您的条件评估为:

while (q02 == 'No') or True or True or True:

显然总是True

要解决此问题,您需要将条件调整为:

while q02 == 'No' or q02 == 'no' or q02 == 'NO' or q02 == 'n':

虽然要更加pythonic,你可以改为:

while q02 in ['No','no','NO','n']:

答案 1 :(得分:2)

问题是while块上的保护条件始终为True

>>> q02 = 'y'
>>> q02 == 'No' or 'no'
'no'

or运算符非常有趣。它评估它的左操作数,如果它是“truthy”,则左操作数是操作的结果;否则,它会评估它的右操作数。在您的情况下,左操作数是布尔值(q02 == 'No'的结果),右操作数是非空字符串。非空字符串是“真实的”,因此这就是结果。

IOW,当{且仅q02 == 'No' or 'no' or 'NO' or 'n'True时,q02评估为'No'。否则,就'no'循环而言,它将评估为字符串while,这是“真实的”。

>>> q02 = 'y'
>>> q02 == 'No' or 'no' or 'NO' or 'n'
'no'
>>> bool(q02 == 'No' or 'no' or 'NO' or 'n')
True

答案 2 :(得分:1)

更改此声明

while q02 == 'No' or 'no' or 'NO' or 'n': 

while q02 == 'No' or q02 == 'no' or q02 == 'NO' or q02 == 'n':

另外一种优雅的方式:

def startMe():
    q01 = input("What is the subject of your note?\n")
    q02 = input("Are you certain that the subject of your note is " + q01 + "?\n")
    negList = ['No', 'no', 'NO', 'nO', 'n', 'N']  # <<< Easily modifiable list.

    while any(q02 in s for s in negList):  
       q01 = input("So, what is the subject of your note?\n")
       q02 = input("Are you certain that the subject of your note is " + q01 + "?\n")
    break:
       q03 = input("Enter the content of your note")

答案 3 :(得分:0)

除1种语法外,您的逻辑和代码是正确的。 使用 while q02 == 'No' or q02 == 'no' or q02 == 'NO' or q02 == 'n': while q02 == 'No' or 'no' or 'NO' or 'n':

的内容

您可以尝试:

def start():
    q01 = input("What is the subject of your note?\n")
    q02 = input("Are you certain that the subject of your note is " + q01 + "?\n")
    while q02 == 'No' or q02 == 'no' or q02 == 'NO' or q02 == 'n':
       q01 = input("So, what is the subject of your note?\n")
       q02 = input("Are you certain now that the subject of your note is " + q01 + "?\n")
    else:
       q03 = input("Enter the content of your note")
start()