[英]How to change a local variable from a sub-function
I have following code:我有以下代码:
my_var=1
def a():
def b():
my_var=2
b()
return my_var
print(a())
I'm trying to change the variable my_var
in sub-function b()
.我正在尝试更改子函数b()
中的变量my_var
。 The result should be 2 instead of 1. But in my code, it doesn't work.结果应该是 2 而不是 1。但在我的代码中,它不起作用。 How can I solve this problem?我怎么解决这个问题?
global
is the keyword used in python to access the actual variable which is present outside function try out the below code. global
是 python 中使用的关键字,用于访问 function 外部存在的实际变量尝试以下代码。
my_var=1
def a():
def b():
global my_var
my_var = 2
b()
return my_var
print(a())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.