【问题标题】:Create Loop in if / else statement在 if / else 语句中创建循环
【发布时间】:2019-11-19 01:18:17
【问题描述】:

我正在尝试循环这个函数,以防出现“else”但我遇到了困难。

我尝试了 while False 并且它不执行打印语句,我猜它一旦最终为 false 就会退出函数。我尝试了 True,我认为这是要走的路,但是当它击中 Else 时,它​​只会重复。我在想......也许我需要做另一个 Elif 来重复整个函数,如果需要,其他的只是一个转义。

def login(answer):
    while False:
        if answer.lower() == "a":
            print("You selected to Login")
            print("What is your username? ")
            break
        elif answer.lower() == "b":
            print("You selected to create an account")
            print("Let's create an account.")
            break
        else:
            print("I don't understand your selection")

【问题讨论】:

标签: python if-statement


【解决方案1】:
while False:

应该是

while True:

否则你永远不会进入循环

进一步:

else:
    print("I don't understand your selection")

应该是:

else:
    print("I don't understand your selection")
    answer = input("enter a new choice")

您甚至可以重构代码以调用不带参数的函数:

def login():
    while True:
        answer = input("enter a  choice (a for login or b for account creation")
        if answer.lower() == "a":
            print("You selected to Login")
            print("What is your username? ")
            break
        elif answer.lower() == "b":
            print("You selected to create an account")
            print("Let's create an account.")
            break
        else:
            print("I don't understand your selection")

【讨论】:

  • 是的,当我执行 elif 时,我意识到答案 = 输入。感谢您的帮助!
  • 查看增强的答案。在其他情况下,您必须要求新的输入。如果不是,您将永远陷入困境。我还建议了一个没有答案参数的替代函数
猜你喜欢
  • 2015-10-28
  • 1970-01-01
  • 2017-02-17
  • 2015-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-07
  • 1970-01-01
相关资源
最近更新 更多