猿问

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

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


我不知道如何让决定函数告诉 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 循环较短。


慕标琳琳
浏览 165回答 2
2回答

守候你守候我

您可以在函数中进行打印并在 while 循环中检查其输出:def decide(greeting):    if greeting == "bye":        print("Bye")        return False  # only break on "bye";    elif greeting == "hi":        print("Hello")    return Truewhile 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

明月笑刀无情

你可以试试这个: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: ")
随时随地看视频慕课网APP

相关分类

Python
我要回答