我不确定为什么这不起作用,但我觉得它与我如何构建while循环有关。我希望循环只有在用户输入的东西不是他们拥有的两个选项时才会继续。但是,即使我通过放入两个正确选择中的任何一个进行测试,while循环也会继续。
prompt = "> "
print "Welcome to the converter. What would you like \
to convert? (temp or distance)"
choice = raw_input(prompt)
while (choice != "temp" or choice != "distance"):
print "Sorry, that's not an option"
choice = raw_input(prompt)
if choice == "temp":
print "temp"
elif choice == "distance":
print "distance"
我在这里缺少什么?提前谢谢。
答案 0 :(得分:2)
你想要选择“临时”或“距离”,所以你的条件应该是它不能(不是“临时”而不是“距离”)。只需在or
条件下替换and
while
。
prompt = "> "
print "Welcome to the converter. What would you like \
to convert? (temp or distance)"
choice = raw_input(prompt)
while (choice != "temp" and choice != "distance"):
print "Sorry, that's not an option"
choice = raw_input(prompt)
if choice == "temp":
print "temp"
elif choice == "distance":
print "distance"
在这种情况发生之前,你的方式总是如此
根据以下建议,您可以编写也适用的while条件:
while not (choice == "temp" or choice == "distance"):
或
while (choice not in ('temp', 'distance')):
选择。