如何使局部变量(在函数内)成为全局变量 [英] How to make a local variable (inside a function) global
本文介绍了如何使局部变量(在函数内)成为全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
在函数中使用全局变量除了创建它们的那个
我使用函数是为了让我的程序不会一团糟,但我不知道如何将局部变量变成全局变量.
解决方案
这里有两种方法可以实现相同的目的:
使用参数并返回(推荐)
def other_function(parameter):返回参数 + 5def main_function():x = 10打印(x)x = other_function(x)打印(x)
当你运行main_function
,你会得到如下输出
使用全局变量(永远不要这样做)
x = 0 # x 的初始值,具有全局作用域def other_function():全球 xx = x + 5def main_function():print(x) # 只是打印 - 还不需要声明全局global x # 所以我们可以改变全局 xx = 10打印(x)其他功能()打印(x)
现在您将获得:
<预><代码>>>>0 # 初始全局值>>>10 # 现在我们在 `main_function()` 中将其设置为 10>>>15 # 现在我们在 `other_function()` 中添加了 5Possible 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:
Using parameters and return (recommended)
def other_function(parameter):
return parameter + 5
def main_function():
x = 10
print(x)
x = other_function(x)
print(x)
When you run main_function
, you'll get the following output
>>> 10
>>> 15
Using globals (never do this)
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)
Now you will get:
>>> 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屋!
查看全文