【问题标题】:How to chain functions to a specific function如何将函数链接到特定函数
【发布时间】:2020-06-25 10:05:16
【问题描述】:

我想将某个函数链接到一个特定函数,该函数只有在前面的函数在 python 中成功执行时才会运行,并且链接的函数不应该在其他地方访问。

示例:我希望仅在名称函数成功运行时才运行问候函数。

def name():
    name = str(input("please enter your name: "))
    while name not in (""," "):
        return name
    def greeting():
        message = "hello {}, welcome".format(name)
        print(message)
        return message
    def happy():
        mood = str(input("hello {},this is to check if you are happy, kindly answer 'yes' or 'no': ".format(name))
        if mood == "yes":
            reply = "that's good"
        else:
            reply = "oh dear, cheer up"
        print(reply)
    else:
        break

info = name()
print(info)

这段代码应该只在name函数执行成功的情况下运行greeting函数并调用happy函数,并且如果没有name函数也不应该调用greeting或happy函数。

但它没有按预期执行。它只返回名称。

提前致谢

【问题讨论】:

    标签: python function while-loop


    【解决方案1】:

    name() 函数中定义其他函数有点不必要。我建议单独定义函数,然后在下面的 while 循环中相应地调用它们。

    def name():
        name = str(input("please enter your name: "))
        if name not in (""," "):
            return name
        return None
    
    def greeting(name):
        message = "hello {}, welcome".format(name)
        print(message)
    
    def happy(name):
        mood = input("hello {},this is to check if you are happy, kindly answer 'yes' or 'no': ".format(name))
        if mood == "yes":
            reply = "that's good"
        else:
            reply = "oh dear, cheer up"
        print(reply)
    
    while True:
        info = name()
        if info:
            greeting(info)
            happy(info)
            break
    

    编辑:我意识到您不希望在 name 函数范围之外访问其他函数。也可以这样做(虽然很奇怪)。

    def name():
        name_ = str(input("please enter your name: "))
        if name_ not in (""," "):
            def greeting(name):
                message = "hello {}, welcome".format(name)
                print(message)
    
            def happy(name):
                mood = input("hello {},this is to check if you are happy, kindly answer 'yes' or 'no': ".format(name))
                if mood == "yes":
                    reply = "that's good"
                else:
                    reply = "oh dear, cheer up"
                print(reply)
                return mood
    
            greeting(name_)
            return name_, happy(name_)
    
        return name()
    
    info = name()
    print(info)
    

    【讨论】:

    • 您好,alec,感谢您的回复。它确实完成了我想要的链接,但我实际上想从名称和快乐函数返回用户输入,但它不会从您的代码返回。
    • @SirBlaze 我编辑了返回值,我想这就是你现在想要的
    猜你喜欢
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 2011-04-26
    相关资源
    最近更新 更多