【问题标题】:How do I call a function which returns a variable, multiple times, while inside another function?如何在另一个函数内部调用多次返回变量的函数?
【发布时间】:2013-05-15 13:13:40
【问题描述】:

我有一个函数(基于文本的游戏),它在整个过程中多次要求输入,在进行错误检查之前,我想立即删除所有空格。

为了减少冗余,我想用另一个函数来做这两件事,然后像这样返回变量:

def startGame():
    print("1, 2 or 3?")
    response = response()

def response():
    a = raw_input()
    a = a.strip()
    return a

startGame()

问题是我不断得到:

UnboundLocalError:赋值前引用了局部变量“response”。

这对我来说毫无意义,因为响应被分配了response() 的返回值。
我错过了什么?有没有更简单的方法来做到这一点?

【问题讨论】:

    标签: python function return user-input


    【解决方案1】:

    你将局部变量命名为responsetoo;你不能这样做,它掩盖了全局 response() 函数。

    重命名局部变量或函数:

    def get_response():
        # ...
    
    
    response = get_response()
    

    def response():
        # ....
    
    received_response = response()
    

    【讨论】:

    • @Martijn_Pieters 谢谢。我不知道 Python 做到了,但现在我做到了!
    • @JosephWebber:在函数中,您直接分配给 (somename = ...) 的所有名称都成为局部变量(语言编译器会这样做)。这不适用于属性 (somename.someattribute = ),仅适用于直接名称。因此response 已经定义为本地名称,但您在为其分配任何值之前尝试使用它。然后引发异常。
    猜你喜欢
    • 2021-10-10
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多