简体   繁体   English

为什么这个while循环不起作用?

[英]Why does this while loop not work?

This loop keeps looping even if I enter "no" and when I type "jdlfjap", for example, it continues to loop without a "?". 例如,即使我输入“ no”,当输入“ jdlfjap”时,该循环也会继续循环,而没有“?”的情况下它将继续循环。

Does anyone know why this is? 有人知道为什么是这样吗?

def makeContact():
    contactName = input("Name: ")
    contactNumber = input("Number: ")
    dictionaryForContacts[contactName] = contactNumber
def continueMaking():
    while True:
        continueMaking = input("\nWould you like to continue making contacts? ")
        if continueMaking == "Yes" or "yes" or "YES":
            makeContact()
            continue
        elif continueMaking == "No" or "no" or "NO":
            break
        else:    
            print ("?")
            continue

The statement if continueMaking == "Yes" or "yes" or "YES": is equivalent to (continueMaking == "Yes") or "yes" or "YES": which, regardless of the value of continueMaking returns the string "YES" , which is truthy and thus the makeContact call always executes. 语句if continueMaking == "Yes" or "yes" or "YES":等效于(continueMaking == "Yes") or "yes" or "YES":不管continueMaking的值如何,该语句都将返回字符串"YES" ,这是事实,因此始终执行makeContact调用。 Case-insensitive string comparisons can be accomplished by continueMaking.lower() == "yes" . 不区分大小写的字符串比较可以通过continueMaking.lower() == "yes"

Overwriting the function continueMaking with the variable continueMaking adds confusion. 覆盖函数continueMaking与可变continueMaking增加混乱。 Choose a different variable name. 选择一个不同的变量名。 Readability counts. 可读性很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM