简体   繁体   English

Python - 使用带有 if/elif 语句的 while 循环

[英]Python - Using a while loop with an if/elif statement

I'm not sure why this isn't working, but I have a feeling it has something to do with how I've structured the while loop.我不确定为什么这不起作用,但我觉得这与我构建 while 循环的方式有关。 I want the loop to continue only if the user inputs something other than the two choices they have.我希望循环仅在用户输入除他们拥有的两个选择之外的其他内容时才继续。 However, even when I test it with putting in either of the two correct choices, the while loop continues.但是,即使我通过放入两个正确选项中的任何一个来测试它,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"

What am I missing here?我在这里缺少什么? Thanks in advance.提前致谢。

You want choice to be either "temp" or "distance", so your while condition should be that it can't (not be "temp" AND not be "distance").您希望选择是“temp”或“distance”,因此您的 while 条件应该是它不能(不是“temp”也不是“distance”)。 Just substitute the or for and on the while condition.只需在while条件下替换or and

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"

The way you had it before the condition would always be true你在条件之前拥有它的方式将始终为真

Per suggestions below other ways you could write the while condition that would also work:根据下面的建议,您可以编写也可以使用的 while 条件的其他方法:

while not (choice == "temp" or choice == "distance"):

or或者

while (choice not in ('temp', 'distance')):

Take your pick.随你挑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM