循环python“if”语句

时间:2012-05-28 02:16:39

标签: python loops if-statement python-3.x

我正在构建一种问题序列作为Python 3.2中程序的一部分。基本上,我提出一个问题并等待两种可能性之间的答案。如果给定的答案不是两个选项的一部分,我打印一行,并希望重新提问,直到给出正确的输入,然后继续下一个问题并重复相同的顺序。

以下是一段可能更好地解释自己的代码:

colour = input("black or white?")
if colour in ["black", "white"]:
    print("Thank you")
else:
    print("Please choose one or the other")

换句话说,如果给定的答案不是黑色或白色,我想打印“请选择一个或另一个”,并重新提问,只要没有给出黑色或白色。一旦给出黑色或白色,我希望它突破if语句,以便我可以用同样的方式提出另一个问题。

我已经搜索了如何做到这一点,但没有找到任何有用的东西。我猜一个循环,但是当我尝试它时,只是无限地吐出我最后一个打印字符串。

2 个答案:

答案 0 :(得分:6)

while True:
  colour = input("black or white? ")
  if colour in ("black", "white"):
    print("Thank you")
    break
  else:
    print("Please choose one or the other")

保留大部分代码,将其包装在无限循环中,并在输入正是您要查找的内容时将其分解。

注意,会员资格测试使用的是tuple而不是list,因为选项不会更改,即不可变,in ("black", "white")会明确显示。

答案 1 :(得分:5)

colour = None
while not colour in ["black", "white"]:
    colour = input("black or white?")

print("Thank you")

或者如果你想得到花哨的话

colour = input("black or white?")
while not colour in ["black", "white"]:
    print("Please choose one or the other")
    colour = input("black or white?")

print("Thank you")