【问题标题】:Python while not true loopsPython while not true 循环
【发布时间】:2022-11-23 05:48:04
【问题描述】:
door = input("Do you want to open the door? Enter yes or no: ").lower()

while door != "yes" and door != "no":
    print("Invalid answer.")
    door = input("Do you want to open the door? Enter yes or no: ").lower()

if door == "yes":
    print("You try to twist open the doorknob but it is locked.")
elif door == "no":
    print("You decide not to open the door.")

有没有更简单的方法来使用 while 循环来获取无效答案?所以我不需要在程序中的每个问题之后添加该行。

我试过 def() 并且虽然是真的,但不太确定如何正确使用它们。

【问题讨论】:

  • 向我们展示您尝试过的 def 方法?将逻辑封装在一个函数中是个好主意(您需要知道如何编写函数。)do while 在这里可能也不错。

标签: python function if-statement while-loop


【解决方案1】:

避免额外行的一种方法:

while True
    door = input("Do you want to open the door? Enter yes or no: ").lower()
    if door in ("yes", "no"):
        break
    print("Invalid answer.")

或者,如果您经常这样做,请创建一个辅助函数。

def get_input(prompt, error, choices):
    while True:
        answer = input(prompt)
        if answer in choices:
            return answer
        print(error)

【讨论】:

    【解决方案2】:
    while True:
        answer = ("Enter yes or no: ").lower()
        if answer in ["yes", "no"]:
            break
        print("Invalid answer.")
        # loop will repeat again
       
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      相关资源
      最近更新 更多