If I have this code:
x = 9
def changex():
x = 10
return x
changex()
print x
when I print x it doesn't say that it is 10, how do I make it so that it is 10 without doing print changex()? Thank you
In Python, if you want code from inside a function to affect global variables, you need to add a global statement:
x = 9
def changex():
global x
x = 10
return x
changex()
print x
You can't change the x object, but you can redefine it:
x = changex()
print x
You could also put global x at the beginning of the function so that it will be redefining the global variable instead of defining a local one.
Related
I have declared global variables that i need to access and modify in a function in a class. This function loops indefinitely once called and stream data passes through it. I need to be able to use x y z variables inside the function, and redefine their values as stream_data comes through.
My current code looks like this:
x = 10
y = 8
z = 2
class Program():
def function(stream_data):
while True:
try:
a = stream_data['data']
if (a - z) > y:
y = a - z
else:
pass
except:
continue
I get error "local variable y defined in enclosing scope on line 7 referenced before assignment".
How can I format this code so that when the function is first called, it uses the global variables, and then on each subsequent calling it uses the variable y it redefined? Thanks I am new to coding and really need help!
Use
global x, y, z to use the global variables
Like This-
x = 10
y = 8
z = 2
class Program():
def function(stream_data):
while True:
try:
global x,y,z
a = stream_data['data']
if (a - z) > y:
y = a - z
else:
pass
except:
continue
Alternatively, you can also initialize x,y,z within your function.
Let me know if this helps!
I got a message 'local variable referenced before assignment'
Use external variable and got OK, but failed to assign value
x = 10
y = 10
def some():
print(x)
some()
10
x = 10
y = 10
def some():
x = 100-x+x
print(x)
some()
local variable 'x' referenced before assignment
x = 10
y = 10
def some():
t=100-x
print(t)
some()
90
x = 10
y = 10
def some():
t=100-x
x=t
print(t)
some()
local variable 'x' referenced before assignment
What's the differences ? Expected result should be the same, but failed in 2nd sample.
Does it mean what I can do just read from 'x', no write to 'x' ?
When you declare a variable inside a function it shadows the variable from the outer scope that has the same name. Once you declared x inside the function it will become the x variable for all the commands in the function, even before the outer scope assignment where x = 10.
If you want to write to the x variable in the outer scope you should declare it as global x, that is
x = 10
y = 10
def some():
global x
x = 100-x+x
print(x)
some()
100
Is there any way to make the python interpreter choose the global variable specifically when there is also a local variable with the same name? (Like C++ has :: operator)
x=50
def fun():
x=20
print("The value of local x is",x)
global x
#How can I display the value of global x here?
print("The value of global x is",x)
print("The value of global x is",x)
fun()
The second print statement inside the function block should display the value of global x.
File "/home/karthik/PycharmProjects/helloworld/scope.py", line 7
global x
^
SyntaxError: name 'x' is used prior to global declaration
Process finished with exit code 1
Python does not have a direct equivalent to the :: operator (typically that kind of thing is handled by the dot .). To access a variable from an outer scope, assign it to a different name as to not shadow it:
x = 50
def fun():
x = 20
print(x) # 20
print(x_) # 50
print(x) # 50
x_ = x
fun()
But of course Python would not be Python if there weren't a hack around this... What you describe is actually possible, but I do not recommend it:
x = 50
def fun():
x = 20
print(x) # 20
print(globals()['x']) # 50
print(x) # 50
fun()
I don't know any way to do this (and I am not an expert). The two solutions that I can think of are to give another name to your local x (like xLoc), or to put your global x in argument, like this :
x=50
def fun(xGlob):
x=20
print("The value of local x is",x)
print("The value of global x is",xGlob)
print("The value of global x is",x)
fun(x)
Is this answering your question ?
I want each key to be in succession of the previous key for this list. For instance, the first key should be 1 and the next will 2, then 3...n for each method call. My code works:
all_randomly_generated_intigers = {}
def new_ID():
y = random.randint(0,5)
x = 0
while x in all_randomly_generated_integers:
x+=1
all_randomly_generated_integers[x] = y
However, the loop will run x times for each call on new_ID(). I figured I could just call x global but my method doesn't see x if I do that:
all_randomly_generated_intigers = {}
global x
def new_ID():
y = random.randint(0,5)
while x in all_randomly_generated_integers:
x+=1
all_randomly_generated_integers[x] = y
Why doesn't this work?
Global x needs to be declared inside the function.
I am trying to understand how closure works in Python.
I feel like add1 should work just fine here. I would expect the variable x to have been defined when helper is called. However, it is giving me a Local variable referenced before assignment error.
add2 is very similar to add1. Instead of assigning x with an integer, it assigns it with a dictionary. The behavior of it is also aligned with what I would expect. x is defined and reference-able inside helper.
import random
def add1():
x = 0
def helper():
x = x + 1
return x
return helper
def add2():
x = {}
def helper():
x[random.randint(1,1000)] = 3
return x
return helper
if __name__ == '__main__':
a1 = add1()
a2 = add2()
# print(a1()) #This causes error
print(a2()) #{650: 3}
print(a2()) #{650: 3, 333: 3}
What's the logic behind this? What am I doing differently other than that the types of x are different?
You're expecting the compiler to know that the variable has been bound outside the closure. This is not true, and hence you need to use nonlocal to indicate this.
def add1():
x = 0
def helper():
nonlocal x
x = x + 1
return x
return helper
EDIT By denniss:
nonlocal is not necessary in add2 because it's just modifying x and not re-binding it (aka not re-assigning it). Whereas in add1, x= x+1 is a re-assignment.