代码之家  ›  专栏  ›  技术社区  ›  multigoodverse

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

  •  0
  • multigoodverse  · 技术社区  · 7 年前

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

    我不知道如何让decise函数告诉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 回复  |  直到 7 年前
        1
  •  0
  •   Krishna    7 年前

    你可以试试这个:

    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: ")
    
        2
  •  0
  •   Viktor Petrov    7 年前

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