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

强颜欢笑 提交于 2019-12-02 01:22:28

Your culprit is the while loop condition:

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

This is equivalent to:

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

As 'no', 'NO' and 'n' are all non-empty strings they evaluate to True and so your condition evaluates to:

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

which is clearly always True.

To fix this you need to adjust the condition to:

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

Although to be more pythonic you could instead make this:

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

The problem is that the guard condition on the while block is always True!

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

The or operator is interesting. It evaluates it's left operand and if it is "truthy" then the left operand is the result of the operation; otherwise, it evaluates it's right operand. In your case, the left operand is a boolean value (the result of q02 == 'No') and the right operand is a non-empty string. The non-empty string is "truthy" so that is the result.

IOW, q02 == 'No' or 'no' or 'NO' or 'n' evaluates to True if and only if q02 is 'No'. Otherwise it evaluates to the string 'no' which is "truthy" as far as the while loop is concerned.

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

Change this statement

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

to

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

One more elegant way of doing it:

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

Your logic and code is correct except 1 syntax. Use while q02 == 'No' or q02 == 'no' or q02 == 'NO' or q02 == 'n': insted of while q02 == 'No' or 'no' or 'NO' or 'n':

You can try:

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() 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!