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

Else-statement after while-statement, and string comparison with a list of strings?

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

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")

更改此声明

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")

你的逻辑和代码是正确的,除了 1 个语法。 采用 [=h11=] 而不是 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() 

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

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

这相当于:

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

由于 'no''NO''n' 都是 non-empty 字符串,它们的计算结果为 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']:

问题是 while 块上的保护条件总是 True!

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

or 运算符很有趣。它评估它的左操作数,如果它是 "truthy" 则左操作数是操作的结果;否则,它评估它的正确操作数。在您的例子中,左操作数是一个布尔值(q02 == 'No' 的结果),右操作数是一个 non-empty 字符串。 non-empty 字符串是 "truthy" 所以这就是结果。

IOW,当且仅当 q02'No' 时,q02 == 'No' or 'no' or 'NO' or 'n' 计算为 True。否则,就 while 循环而言,它的计算结果为字符串 'no',即 "truthy"。

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