0

我一直在使用这个 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()
4

1 回答 1

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":
于 2013-10-18T02:08:28.490 回答