如何使局部变量(在函数内部)成为全局变量 [英] How to make a local variable (inside a function) global
本文介绍了如何使局部变量(在函数内部)成为全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
在函数中使用全局变量除了创建它们的那个
Possible Duplicate:
Using global variables in a function other than the one that created them
我正在使用函数,以便我的程序不会一团糟,但我不知道如何将局部变量变成全局变量.
I'm using functions so that my program won't be a mess but I don't know how to make a local variable into global.
推荐答案
这里有两种方法可以实现相同的目的:
Here are two methods to achieve the same thing:
使用参数并返回(推荐)
def other_function(parameter):
return parameter + 5
def main_function():
x = 10
print x
x = other_function(x)
print x
运行main_function
时,将获得以下输出
When you run main_function
, you'll get the following output
>>> 10
>>> 15
使用全局变量(从不这样做)
x = 0 # The initial value of x, with global scope
def other_function():
global x
x = x + 5
def main_function():
print x # Just printing - no need to declare global yet
global x # So we can change the global x
x = 10
print x
other_function()
print x
现在您将获得:
>>> 0 # Initial global value
>>> 10 # Now we've set it to 10 in `main_function()`
>>> 15 # Now we've added 5 in `other_function()`
这篇关于如何使局部变量(在函数内部)成为全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文