代码之家  ›  专栏  ›  技术社区  ›  A.Wittkamp

调用自身后,Python函数将无法正确返回。为什么?[副本]

  •  0
  • A.Wittkamp  · 技术社区  · 7 年前

    我在做一个文字冒险游戏。打印标题后,下面的功能提示玩家按“y”开始游戏。如果输入“y”,函数将返回“打开”。如果没有,函数会建议他们注意自己的输入,并调用自己重新开始。

    如果玩家第一次点击“y”,该函数将正确返回。我遇到的问题是,如果玩家输入了错误的输入,随后尝试输入“y”的操作将无法正确返回。它们跳到函数的底部,并返回我的错误消息“this is wrong”。

    如何让函数在调用自身后正确返回?

    def prompt():
    
        print "Hit 'Y' to begin."
    
        action = raw_input("> ").lower()
    
        if action == "y":
            return "opening"
    
        else:
            print "For this game to work, you're going to have to get"
            print "the hang of hitting the right key."
            print "Let's try that again."
            prompt()
    
        return "this is wrong"
    
    ret = prompt()
    print ret
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Eamonn McEvoy    7 年前

    您只是再次调用函数,但没有返回值,应该是

        print "Let's try that again."
        return prompt() 
    

    但是,您根本不应该递归地执行此操作。。。

    def prompt():
    
        print "Hit 'Y' to begin."
    
        action = raw_input("> ").lower()
    
        while action != "y":
            print "For this game to work, you're going to have to get"
            print "the hang of hitting the right key."
            print "Let's try that again."
            action = raw_input("> ").lower()
    
        return "opening"
    ret = prompt()
    print ret
    
        2
  •  0
  •   aiven    7 年前

    使用 return prompt() 内部功能