有条件执行多重比较不起作用

时间:2013-10-18 02:04:51

标签: python loops dictionary while-loop

我遇到了这个python代码的问题。我刚刚开始编码,我无法弄清楚它为什么不起作用。我不能让循环停止重复。无论我输入什么,它都会启动add_item功能。有什么提示吗?

supply = { #Creates blank dictionary
}
print "Would you like to add anything to the list?"

def add_item(*args):     #Adds a item to the supply dictionary
    print "What would you like to add?"
    first_item = raw_input()
    print "How much does it cost?"
    first_price = raw_input()
    supply[first_item] = float(first_price)

response = raw_input()

while response == "yes" or "Yes" or "YES":
    if response == "yes" or "Yes" or "YES": #Added this because it wasn't working, didn't help
        add_item()
        print "Alright, your stock now reads:", supply
        print "Would you like to add anything else?"
        response = raw_input()
    elif response == "no" or "No" or "NO":
        print "Alright. Your stock includes:" 
        print supply
        break
    else:
        print "Sorry I didn't understand that. Your stock includes:" 
        print supply
        break

print "Press Enter to close"
end_program = raw_input()

1 个答案:

答案 0 :(得分:6)

您似乎对or的工作方式感到困惑。

您的原始表达可以像这样重写:

(response == "yes") or ("Yes") or ("YES")

也就是说,它测量了三个表达式的真实性:等式表达式, 和剩下的两个字符串表达式中的每一个。 "Yes""YES"都会得到审核 是的,所以你(或多或少)有:

while (response == "yes") or True or True:

由于"Yes"总是评估为真, while表达总是正确的。

尝试:

while response in ( "yes" , "Yes" , "YES"):

或者,更好的是:

while response.lower() == "yes":