Python报错SyntaxError: name ‘xxx‘ is assigned to before global declaration解决方法

错误场景

我在main函数中用global关键字声明了全局变量,希望其他的函数都能调用这个全局变量。

以下为错误代码的示例。

targetDir = ''


def test_function():
    # 在自定义函数中调用全局变量
    filepath = targetDir + '\\output1.csv'
    print(filepath)


def test_function_1():
    # 在自定义函数中调用全局变量
    filepath = targetDir + '\\output2.csv'
    print(filepath)


if __name__ == '__main__':
    # 给全局变量赋值
    global targetDir
    targetDir = 'D:\\Test\\user'
    test_function()
    test_function_1()

报错:SyntaxError: name 'targetDir' is assigned to before global declaration

发生错误的位置是main函数中global targetDir这一行。

解决方法

错误原因是,在main函数不需要添加global关键字来声明全局变量。

因此解决方法是,直接赋值就可以了,函数体外侧的声明也不是必须的。

以下为正确的代码示例。

def test_function():
    filepath = targetDir + '\\output1.csv'
    print(filepath)


def test_function_1():
    filepath = targetDir + '\\output2.csv'
    print(filepath)


if __name__ == '__main__':
    targetDir = 'D:\\Test\\user'
    test_function()
    test_function_1()

问题延申

假设在函数a中定义了一个值,想要在函数b中访问,那么可以在函数a中通过global关键字声明为全局变量。

def test_func_a():
    # 给全局变量赋值
    global targetDir
    targetDir = 'D:\\Test\\user'


def test_func_b():
    # 调用变量targetDir
    filepath = targetDir + '\\outputData.csv'
    print(filepath)


if __name__ == '__main__':
    test_func_a()
    test_func_b()

输出结果是: D:\Test\user\outputData.csv,结果符合预期。

如果把函数a中global targetDir这一行声明去掉,b就访问不到a赋的值了。

  • 12
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值