【问题标题】:How to send a break statement from a function to a while loop?如何将break语句从函数发送到while循环?
【发布时间】:2019-05-10 15:23:59
【问题描述】:

我试图反复要求用户输入一个字符串。如果该字符串是“再见”,程序应该返回“再见”并终止。

我不知道如何让决策函数告诉 while 循环该终止了。

def decide(greeting):
    if greeting == "hi":
        return "Hello"
    elif greeting == "bye":
        return "Bye"

x = input("Insert here: ")
while True:
    print(decide(x))
    x = input("Insert here: ")

编辑:cmets 中的人说要在 while 循环中使用条件来检查返回值。我不能这样做,因为实际上返回的值"Bye" 存储在局部变量中。这两个函数实际上在一个类中,我更愿意在条件上保持 while 循环简短。

【问题讨论】:

  • 为什么不能在while循环中检查返回的字符串退出?
  • 就像@Krishna 说的那样,在while 内执行if 以检查返回值,并相应地检查break
  • @Krishna 请查看我的编辑。
  • @Viktor Petrov 建议的答案怎么样。那可行吗?还是我错过了什么?

标签: python while-loop exit break


【解决方案1】:

您可以在函数中进行打印并在 while 循环中检查其输出:

def decide(greeting):
    if greeting == "bye":
        print("Bye")
        return False  # only break on "bye";
    elif greeting == "hi":
        print("Hello")
    return True

while True:
    x = input("Insert here: ")
    if not decide(x):
        break

EDIT 基于已澄清的问题(函数内部没有打印)。您的函数可以有多个输出,例如:

def decide(greeting):
    if greeting == "bye":
        return "Bye", False  # return reply and status;
    elif greeting == "hi":
        return "Hello", True
    else:
        return greeting, True  # default case;

while True:
    x = input("Insert here: ")
    reply, status = decide(x)
    print(reply)
    if not status:
        break

【讨论】:

  • 解码函数实际上是在一个类中。最终输出将是包含这些 Hello 和 Byes 的 JSON 字符串。因此,在类中包含 print() 函数并没有任何好处。我只想为函数提供一个字符串,并让该函数 return 取决于该字符串。
  • 这是您在最初问题中遗漏的大部分难题,可能值得包含您的实际类代码,因为您的问题可能有更优雅的解决方案。我已经更新了我的答案,以便决定函数返回回复字符串的值和一个状态布尔值,您可以使用它来确定是否应该中断循环。另一种方法是遵循@Krishna 的建议,并在您的 while 循环中添加另一个 if 语句。
【解决方案2】:

你可以试试这个:

def decide(greeting):
    if greeting == "hi":
         return "Hello"
    elif greeting == "bye":
        return "Bye"

x = input("Insert here: ")

while True:
    n = (decide(x))
    print(n)

    if(n == "Bye"):
        break

    x = input("Insert here: ")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-17
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    相关资源
    最近更新 更多