【问题标题】:Python - Using a while loop with an if/elif statementPython - 使用带有 if/elif 语句的 while 循环
【发布时间】:2016-02-16 03:12:39
【问题描述】:

我不确定为什么这不起作用,但我感觉这与我构建 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"

我在这里缺少什么?提前致谢。

【问题讨论】:

  • 如果您希望if 语句成为while 循环的一部分,您需要将它放在相同的缩进级别。
  • 看来你才刚开始学习python,你真的应该学习python 3,它已经出了10年了,怪癖更少,功能更多。
  • @SethMMorton 这不是他想要的。 while 循环只是不断要求一个新值,直到提供一个有效的值
  • 如果我的回答解决了您的问题,请采纳。如果它没有让我知道还有什么问题,我会尽力帮助你解决它

标签: python if-statement while-loop


【解决方案1】:

您希望选择“temp”或“distance”,因此您的 while 条件应该是它不能(不是“temp”而不是“distance”)。只需在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"

在条件为真之前你拥有它的方式总是正确的

根据以下建议,您可以编写也可以使用的 while 条件:

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

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

任你选。

【讨论】:

  • Psst:DeMorgan 定律将大大提高条件的可读性。
  • 当然,另一个选项是choice not in ('temp', 'distance')
  • @dietbacon,谢谢!这是有道理的——我基本上用 while 语句创建了一个无限循环,因为无论选择什么都是“非距离”或“非临时”。你解释得很好。我将“或”更改为“和”,现在一切正常。
  • @MasterModnar 没问题,这就是我们来这里的目的 :)
猜你喜欢
  • 2021-04-15
  • 1970-01-01
  • 1970-01-01
  • 2012-12-02
  • 2020-04-10
  • 2021-03-18
  • 2021-10-31
  • 1970-01-01
  • 2012-03-12
相关资源
最近更新 更多