如何将break语句从函数发送到while循环?

时间:2018-12-09 15:03:54

标签: python while-loop exit break

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

我无法弄清楚如何使Decision函数告诉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: ")

编辑:注释中的人们说要在while循环中使用条件语句来检查返回的值。我不能这样做,因为实际上返回的值"Bye"存储在局部变量中。现实中,这两个函数都在类中,我更喜欢在条件条件上简化while循环。

2 个答案:

答案 0 :(得分:0)

您可以在函数中进行打印,并在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

编辑(基于已澄清的问题)(功能内无打印内容)。您的函数可以有多个输出,例如:

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

答案 1 :(得分:0)

您可以尝试以下方法:

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: ")