2015-11-07 83 views
0

即使我输入“no”,并且当我输入“jdlfjap”时,该循环仍然保持循环,例如,它会继续循环而没有“?”。为什么while while循环不起作用?

有谁知道这是为什么?

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 
+0

'continueMaking ==“No”或“no”或“NO”'不会做你认为它做的事。它不会比较这3个单词中的每一个的“continueMaking”。 – lurker

+0

使用'lower()'或checkout ['in'](https://docs.python.org/3/reference/expressions.html#in) – sam

+0

重写为'if continueMaking in(“Yes”,“yes” ,“YES”)'或'if continueMaking.strip()。lower()==“yes”' – dawg

回答

2

声明if continueMaking == "Yes" or "yes" or "YES":相当于(continueMaking == "Yes") or "yes" or "YES":其中,无论continueMaking值返回字符串"YES",这是truthy,因此makeContact呼叫始终执行。不区分大小写的字符串比较可以通过continueMaking.lower() == "yes"完成。

+0

我现在明白了。谢谢!!! – Daniel

+1

好的答案,但可能应该是'continueMaking.strip()。lower()==“yes”'来捕捉尾随空格。 – dawg

+0

基于[运算符优先顺序](https://docs.python.org/2/reference/expressions.html),为什么不计算为'continueMaking == true',因为'或'具有更高的优先级并且它会被强制为一个布尔值? – BLaZuRE

1

覆盖函数continueMaking与变量continueMaking增加了困惑。选择一个不同的变量名称。可读性计数。