python变量如何声明为全局变量
这篇文章给大家分享的是有关python变量如何声明为全局变量的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
1、在函数内部分配变量并使用global line。
def declare_a_global_variable(): global global_variable_1 global_variable_1 = 1 # Note to use the function to global variables declare_a_global_variable()
2、在函数外赋值。如果想在另一个函数中更改global line,update_variables()应该在分配变量之前使用global。
global_variable_1 = 1 global_variable_2 = 2 def update_variables(): global global_variable_1 global_variable_1 = 11 global_variable_2 = 12 # will update just locally for this function update_variables() print(global_variable_1) # prints 11 print(global_variable_2) # prints 2
感谢各位的阅读!关于“python变量如何声明为全局变量”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!