0 python dictionary loops 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()
Run Code Online (Sandbox Code Playgroud)
你似乎对如何or运作感到困惑.
您的原始表达式可以像这样重写:
(response == "yes") or ("Yes") or ("YES")
Run Code Online (Sandbox Code Playgroud)
也就是说,它测量了三个表达式的真实性:等式表达式,以及剩下的两个字符串表达式中的每一个.双方"Yes"并"YES"evaulate为真,所以你(更多或更少)有:
while (response == "yes") or True or True:
Run Code Online (Sandbox Code Playgroud)
由于"Yes"始终计算为true,因此while表达式始终为true.
尝试:
while response in ( "yes" , "Yes" , "YES"):
Run Code Online (Sandbox Code Playgroud)
或者,更好的是:
while response.lower() == "yes":
Run Code Online (Sandbox Code Playgroud)