[英]python and assigning variable values in if statements
I'm somewhat of a beginner in python and I swear I got a very similar program to what I'm doing right now to work. 我有点像python的初学者,我发誓我得到了一个非常类似于我现在正在做的工作。 But, for some reason, I can't make it work. 但是,由于某种原因,我无法使其发挥作用。 I was able to pinpoint my problem and created a fake program to play around with it. 我能够找出我的问题,并创建了一个假的程序来玩它。 Here is what the program: 这是程序:
global heading
global heading2
global a
heading=2
a=2
heading2=4
def function ():
if a==2:
heading=heading2
print 'yes'
print heading
function()
print heading
This is what appears: 出现的是:
yes
4
2
Why doesn't the heading variable heading keep the value 4? 为什么标题变量标题不保持值4? I tried putting return heading all over. 我试着将返回标题全部放进去。 Didn't work. 没工作。 I tried putting the variables in the parentheses of the function. 我尝试将变量放在函数的括号中。 Didn't work either... Do you know what I'm doing wrong? 也没工作......你知道我做错了什么吗?
global
statement is meaningless outside of a function. global
陈述在函数之外是没有意义的。 If you want to modify the global variable, instead of introducing a local one, you need to put global
inside the function 如果要修改全局变量,而不是引入本地变量,则需要将global
放在函数内部
def foo():
global x
x = x2
Also, don't use globals. 另外,不要使用全局变量。
The line: 这条线:
heading=heading2
Creates a new local variable called heading
, which is different to the other varaible called heading
that you passed into the function. 创建一个名为heading
的新局部变量,它与您传递给函数的另一个名为heading
变量不同 。
You can make the function assign to external variables by adding: 您可以通过添加以下内容将函数分配给外部变量:
global heading
before you assign to heading: 在分配到标题之前:
def function():
global heading
if a==2:
heading=heading2
print 'yes'
print heading
Inside function, you are creating a local variable called heading
. 在函数内部,您将创建一个名为heading
的局部变量。 This isn't the same heading
declared outside of the function. 这与函数外部声明的heading
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.