1 i = 0
2 def global_test():
3     i+= 1
4     print(i)
5 global_test()
报错 UnboundLocalError: local variable 'i' referenced before assignment
分析:global关键字用来在函数或其他局部作用域中使用全局变量。但是如果不修改全局变量也可以不使用global关键字,如果修改必须使用global进行定义 如下:
1 i = 0
2 def global_test():
3     global i
4     i+= 1
5     print(i)
6 global_test()
7 print(i)

输出结果:1 1

 

相关文章:

  • 2022-12-23
  • 2021-06-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-05
  • 2021-07-23
猜你喜欢
  • 2022-12-23
  • 2021-08-20
  • 2021-11-29
  • 2022-01-10
  • 2021-12-29
相关资源
相似解决方案