Python variables outside function [duplicate] - python

This question already has answers here:
Using global variables in a function
(25 answers)
Closed 7 years ago.
I'm trying to access the counter variable in my function, why doesn't it work and how do I resolve it?
Relevant code:
sum = 0
counter = 0
def newFibo(a, b) :
if(counter > 4000000) :
return
c = a + b
sum += c
counter +=1
newFibo(b,c)
newFibo(1,2)
print(sum)
error: "local variable 'counter' referenced before assignment"

In Python, if you want to modify a global variable inside a function, you have to declare it as global inside the function:
def newFibo(a, b) :
global counter, sum
..............
Note that you don't need it if the variable is only read inside the function but not modified.

You need to use the keyword global to tell python that a variable is outside the current function.
So, basically, add global sum, counter right after def newFibo(a, b):.

Related

Why isn't Python recognizing my declared variable as a global variable? [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
Closed last year.
I am new to Python. I declared a variable named 'total' outside the function and then I called it inside my function called 'my_function'. But it is giving me an error because my variable 'total' is not global. Why is that? I thought variables declared outside were already considered global.
total = 1
def my_function(list):
for i in list:
total = total + 1
print (total)
my_function([1,2,3])
You need to use the global keyword in your function
total = 1
def my_function(list):
global total
for i in list:
total = total + 1
print(total)
my_function([1, 2, 3])
Output:
2
3
4

How can I manage the scope problem in Python [duplicate]

This question already has answers here:
Python function global variables? [duplicate]
(6 answers)
Closed last year.
I have the following code:
x = 1
def increaseX(number):
x += number
increaseX(2)
print(x)
I want to increase a glob variable via the function increaseX, what is the best way to do this?
global keyword is what you need:
x = 1
def increaseX(number):
global x
x += number
increaseX(2)
print(x)
Otherwise, Python tries to find x in local namespace because of += (something like x = x + number) and because in the right hand side of the assignment there is no x defined, you will get :
UnboundLocalError: local variable 'x' referenced before assignment
I tried this and it works, but I don't feel this is the best way
x = 1
def increaseX(number):
global x
x += number
increaseX(2)
print(x)

Using Python's "plus equals" operator on a global variable with a function [duplicate]

This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Using global variables in a function
(25 answers)
Closed 1 year ago.
As the title suggests, when I try to execute this function:
num = 3
def add_num():
num += 6
print(num)
add_num()
print(num)
it gives this error:
Traceback (most recent call last):
File "C:/Users/Sean/Desktop/Programming/Python_prac/test.py", line 9, in <module>
add_num()
File "C:/Users/Sean/Desktop/Programming/Python_prac/test.py", line 5, in add_num
num += 6
UnboundLocalError: local variable 'num' referenced before assignment
What confuses me is that you can reference "num" within the function once you don't try to assign it to itself. However, wouldn't the "num" variable created in the function just point to another location in memory and this not be an issue?
Could someone explain this behavior.
If you try to reference a global variable or call any of its methods from within a function then it will work fine. But the problem comes when trying to change one - the += operator doesn't actually change the value stored in memory because ints are immutable. Therefore, it creates a new variable, also with the name num, equal to the previous value plus 6. But when Python sees any operator to create a new variable of a certain name within a function, it immediately assumes you are trying to reference the local variable as opposed to the global one. To fix this, use the global keyword:
num = 3
def add_num():
global num
num += 6
print(num)
add_num()
print(num)
What's even more odd is the fact that even if the line creating a new variable with name num were to be right at the bottom of the function, trying to reference num at the top of the function would still give a syntax error because Python sees the = operator at the bottom of the function even when still at the top of the function:
def add_num():
print(num) # Gives a syntax error
num = 5
num = 3
def add_num():
global num
num += 6
print(num)
add_num()
print(num)
will do
That's because you num variable scope is local to the function.
In order to be able to access the global num variable, you have to leverage the global keyword:
um = 3
def add_num():
global num
num += 6
print(num)
add_num()
print(num)
Output:
9
To use the variable that is not inside the scope of a function, we can use global keyword to use it.
num = 3
def add_num():
global num
num += 6
print(num)
add_num()
print(num)

Python mixing global and local variable? [duplicate]

This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 4 years ago.
I initialize a global variable 'i' to 0 and a function definition.
In the def, I want to initialize local 'j' to global 'i' and then assign 1 to global 'i', but the compliler thinks when I assign 1 to 'i', I initialize it.
this is not working:
i = 0
def doSomething():
j = i # compiler throws UnboundLocalError here
i = 1
and this is working:
i = 0
def doSomething():
j = i
You need to declare the global variable within the function before modifying.
i = 0
def doSomething():
global i #needed to modify the global variable.
j = i # compiler throws UnboundLocalError here
i = 1

Why am I getting a local variable referenced before assignment error? [duplicate]

This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 6 years ago.
The answer should be 2 because first the main() function is called, then the first() function is called, overriding the global variable num = 0 which was defined outside of any functions, therefore rendering it a variable with global scope. Yet I get the following error:
UnboundLocalError: local variable 'num' referenced before assignment
Why am I getting this error?
def first():
num = num + 1
def main():
num = 1
first()
print(num)
num = 0
num_result = main()
print(num_result)
The OP wrote (emphasis mine):
The answer should be 2 because first the main() function is called, then the first() function is called, overriding the global variable.
It is not overriding the global variable. Unless you explicitly specify a variable as global, if there is any assignment to the variable in a function, it is assumed to be local. See also the python tutorial on defining functions where it states (emphasis mine):
More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.
and the documentation of the global statement (if anyone using Python 3 is looking at this, please also take a look at the (compared to global) very useful nonlocal statement and its PEP 3104).
To "fix" your code:
def first():
global num
num = num + 1
def main():
global num
num = 1
first()
print(num)
num = 0
num_result = main()
print(num_result)
Do not use global variables in this way please. #LutzHorn has shown in his answer how to do it right.
The reason to avoid global variables is that their effect is hard to test for, and as soon as code gets complex enough, hard to reason about. If every function modifies global variables instead of properly taking parameters and returning values, understanding what the code actually does is hard as soon as one has more than a week or so of distance from it.
Inside first, num is not known. Use arguments and return statements.
def first(num):
return num + 1
def main():
num = 1
num = first(num)
return num
num = 0
num_result = main()
print(num_result)
This is a scope error. In first, there is no num before you try to add one to it. You can call a variable in a bloc if it is declared in this bloc, in an upper bloc or if it is declared global.
To pass variables, you can use arguments of the function:
def first(num):
return num + 1
def main():
shmilblik = first(1)
print(shmilblik)
"num" is not defined in the function "first". It is not a global variable, it is out of the scope of "first". To make it global just edit your function like this:
def first():
global num
num = num + 1
Using globals is bad practice in my opinion. you could achieve the same by using parameters and a return like this:
def first(num):
return num + 1
def main(num):
num = 1
num = first(num)
print(num)
return num
num = 0
num_result = main(num)
print(num_result)
The variable num is just initialized in the main-method, you're not initializing it in the first()-Method. So you've to hand it over to the first()-Method.
def first(num):
return num + 1
def main():
num = 1
num = first(num)
return num
num = 0
num_result = main()
print(num_result)

Categories

Resources