Accessing global variable in function in python - python-3.x

I have two pieces of code:
def g(y):
print(x)
x = 5
g(x)
and
def h(y):
x = x + 1
x = 5
h(x)
The first piece of code works perfectly fine printing '5' while the second piece returns:
UnboundLocalError: local variable 'x' referenced before assignment
What does this actually mean? Is it trying to say that it tried to evaluate the line x = x + 1 before it evaluates the line x=5? If that is so, why has the first piece of code not generated any error? It similarly had to evaluate the line print(x) before x was assigned a value.
I think I might have an misunderstanding how functions are called. But I do not know what it is that I got wrong.

# first block: read of global variable.
def g(y):
print(x)
x = 5
g(x)
# second block: create new variable `x` (not global) and trying to assign new value to it based on on this new var that is not yet initialized.
def h(y):
x = x + 1
x = 5
h(x)
If you want to use global you need to specify that explicitly with global keyword:
def h(y):
global x
x = x + 1
x = 5
h(x)

Just as Aiven said, or you can modify the code like this:
def h(y):
x = 9
x = x + 1
print(x) #local x
x = 5
h(x)
print(x) #global x

Related

How to enact pass by reference in python as we do in C/C++?

x,y = 30,40
def swap(x,y):
x = x+y
y = x-y
x = x-y
print(x,y) #Here it swaps but as soon as function ends they go back to their previous values
swap(x,y)
print(x,y) #still prints x as 30 and y as 40
In C/C++ we used & operator to pass their addresses to make this change, how can we do the same thing in python considering python follows pass by object reference model?

PYTHON 3:UnboundLocalError local variable 'x' referenced before assignment

this code gave this error: UnboundLocalError: local variable 'x' referenced before assignment
def predict_price(location,sqft,bath,BHK):
loc_index = numpy.where(x.columns==location)[0][0]
x = numpy.zeros(len(x.columns))
x[0] = sqft
x[0] = bath
x[0] = BHK
if loc_index >=0:
x[loc_index] = 1
return lr_clf.predict([x])[0]
predict_price("calabar",1000, 2, 2)
The issue is that you are referencing x.columns in the initializer.
x = numpy.zeros(len(x.columns))
In other words, you are defining x based on the length of columns in x. If x is not yet defined, then how is it possible to determine how many columns it has?

How are the values being determined in this basic Python class?

I am new to Python and to OOP concept. I was doing a EdX course and came across this code. I have modified it a little bit here. But I need to understand what exactly is happening here.
Question-1: Why does print(baba.x) give 7 but not 3?
Question-2: What does print(X) (capital X) do here? In getX and init I am using 'x' and not 'X'. So where does print(X) get its value from? It seems it is getting this value from the X=7 assignment. But isn't that assignment happening outside of the method getX and also outside of the class Weird. So why is getX able to access X=7 value?
I have searched on scope in Python, but was getting too complicated for me.
class Weird(object):
def __init__(lolo, x, y):
lolo.y = y
lolo.x = x
def getX(baba,x):
print (baba.x)
print (x)
print (X)
X = 7
Y = 8
w1 = Weird(X, Y)
print(w1.getX(3))
The output of the above code is:
7
3
7
None
Read What is the purpose of the word 'self', in Python?
class Weird(object):
def __init__(self, x, y):
self.y = y
self.x = x
def getX(self,x):
print (self.x) # this is the x value of this instance
print (x) # this is the x value you provide as parameter
print (X) # this might read the global X
X = 7
Y = 8
w1 = Weird(X, Y) # this sets w1.x to X (7) and w1.y to Y (8)
print(w1.getX(3)) # this provides 3 as local x param and does some printing

Perplexed over a simple function in Python

Look at the code below:
def foo (x):
print("foo environment: x = {0}".format(x))
def bar (z, x = 0):
print("bar environment: z = {0} and x = {1}. Value to be returned: {2}".format(z, x, x+z))
return z + x
return bar(3)
foo(5)
foo environment: x = 5
bar environment: z = 3 and x = 0. Value to be returned: 3
3
Since in the foo environment x = 5, why bar uses the value 0?
You are only passing one argument here:
return bar(3)
The bar function accepts two values, one z and one x (x has a default value (0) and that is why only 1 argument is enough). By only passing the z, x=0.
Try this, and see what happens:
return bar(3, x)

how to define a certain value to equal to constant just for the first iteration?

I have a the following code (as an example):
answ = []
for i in range(1, 3):
x = y + 2
y = 3 + x
answ.append(y)
Where x and y are simultaneously determined. How can I determine them simultaneously? Or how can I assume that for the first loop y=0 (so x will equal to 2) and then starting from the second iteration 'y' = 3 + x.
Just set y to 0 before the for loop:
answ = []
y = 0
for i in range(1, 3):
x = y + 2
y = 3 + x
append.answ(y)
Like this:
x, y = y + 2, 3 + x
Right now, x and y are local variables, meaning they are deleted at the end of each iteration of the for loop. If you want them to carry over from the previous iteration, you need to define x and y outside of the for loop. This puts them above and the scope of the loop, so they don't get redefined.
Another thing, your for loop runs 2 times, because computers count from 0 and don't include the last number. Because i is not used in your loop at all, it would be better to do:
for i in range(2):
# code
But I am guessing that you want your loop to run three times, in which case you would write:
for i in range(3):
# code
I also noticed that you wrote append.answ(y) instead of answ.append(y). append is a member function of answ, so you would call it the second way.
Anyways, here is the final code for your program:
answ = []
x = 0
y = 0
for i in range(3):
x = y + 2
y = 3 + x
answ.append(y)

Resources