Change value of global variable input into a defined function [duplicate] - python

This question already has answers here:
How do I pass a variable by reference?
(39 answers)
Closed 2 years ago.
I want function(x) to change the value of whatever global variable is put into it, say add one to the variable, like so:
>>> a = 1
>>> function(a)
>>> print(a)
2
I tried:
def function(x):
global x
x = x + 1
However, this returns a SyntaxError name 'x' is parameter and global...

a=1 #global variable
def function():
global a
a=a+1 #operation on variable a
return a
function()
is this answer your query?

Related

I've attached my code. Please review it and tell me the reason of the error. Explain it? [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 2 years ago.
My code
x = 10
def fun():
x = x + 2
print(x)
fun()
print(x)
And the output error
UnboundLocalError: local variable 'x' referenced before assignment
You have to pass global x in the def fun() as no variable named x is assigned in fun(). Here is the code:
x = 10
def fun():
global x
x = x + 2
print(x)
fun()
print(x)
Output
>>> 12
>>> 12
OR
You can also simply pass an argument, but this makes a difference in the values of x:
x = 10
def fun(x):
x = x + 2
print(x)
fun(x)
print(x)
Output
>>> 12
>>> 10
Your variable x, that you're trying modify in the function fun(), is of global scope. Hence, you can't access it inside the function like that. However, you can use:
x = 10
def fun():
global x
x = x + 2
print(x)
fun()
print(x)
Appending global x, will allow the function to modify the variable x which is in global scope.
You don't give x as the parameter to the function. That's why.
x = 10
def fun(x):
x = x + 2
print(x)
fun()
print(x)

Understanding scope of a variable defined in global scope in python [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 2 years ago.
num = 0
def func():
print(num)
func()
The above function is supposed to print the value held by variable num and it works. By this, i would assume that func has access of num. But when i try to change the value of num inside the function, it gives me an error. UnboundLocalError: local variable 'num' referenced before assignment
num = 0
def func():
print(num)
num += 1
func()
Why is this happening?
The num variable isn't in the function's local scope, so you can't modify it inside the function since the variable contains an immutable data type (int).
You can take advantage of global keyword or define the variable inside the function.
num = 0
def func():
global num
print(num)
num += 1
func()

Why is a global dictionary accessible inside a class whereas a global integer variable is not? [duplicate]

This question already has answers here:
Global dictionaries don't need keyword global to modify them? [duplicate]
(2 answers)
Why is the global keyword not required in this case? [duplicate]
(1 answer)
Closed 2 years ago.
I have declared a dictionary globally and a variable as well. Now, when accessing both in a class, I can access the dictionary but for accessing the other variable, I get the UnboundLocalError. For solving this, I used the line of code: global curr_length and then access it and it ran. But I wanted to known why is this additional line of code required for a normal integer variable whereas not required for a dictionary?
The code is:
memoized = {}
curr_length = 0
curr_pal = ""
class Solution:
def check_palindrome(self, str_):
if len(str_) <= 1:
return False
global curr_length
if len(str_) <= curr_length:
return False
if memoized.get(str_, None):
return memoized[str_]
if str_ == str_[::-1]:
memoized[str_] = True
curr_length = len(str_)
return True
memoized[str_] = False
return False
def longest_palindrome(self, str_, starting_index):
if len(str_) <= 1:
return None
n = len(str_)
if self.check_palindrome(str_[starting_index:n]):
return str_
n -= 1
self.longest_palindrome(str_[starting_index:n], starting_index)
def longestPalindrome(self, s: str) -> str:
for starting_index in range(len(s)):
pal = self.longest_palindrome(s, starting_index)
if pal:
return pal
return ""
solution = Solution()
print(solution.longestPalindrome("babad"))
Short:
You are trying to change the value of curr_length with curr_length = len(str_) inside a function which looks for a local curr_length variable, and can't find it. It needs the line global curr_length to know that it's a global variable.
As far as why you're wondering as to why a dict object does not need global memoized line, you should read the answer to:
Global dictionaries don't need keyword global to modify them? or Why is the global keyword not required in this case?
EXPLANATION:
In Python, a variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function.
Let's see an example on how a global variable is created in Python.
x = "global"
def foo():
print("x inside :", x)
foo()
print("x outside:", x)
When we run the code, the will output be:
x inside : global
x outside: global
In above code, we created x as a global variable and defined a foo() to print the global variable x. Finally, we call the foo() which will print the value of x.
What if you want to change value of x inside a function?
def foo():
x = x * 2
print(x)
foo()
When we run the code, the will output be:
UnboundLocalError: local variable 'x' referenced before assignment
The output shows an error because Python treats x as a local variable and x is also not defined inside foo().
To make this work we use global keyword

Weird error in python regarding scoping [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.
x = 5
def foobar():
print (x) #Prints global value of x, which is 5
x = 1 #assigns local variable x to 1
foobar()
Instead, it throws a
UnboundLocalError: local variable 'x' referenced before assignment
What am I misunderstanding in the comments? Note, I understand if i do x=x+1, it'll throw error due to 'accessing value of local scope x beforei it's defined', but in this case I'm doing x=1, which does not require reading of existing value of x! This is NOT a duplicate question.
If you want to change a global variables value in a function in python, you have to do
x = 5
def foobar():
global x
print (x) #Prints global value of x, which is 5
x = 1 #assigns local variable x to 1
foobar()

Using global variable inside a python 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)
Closed 6 years ago.
So here is the code that uses x inside a function.
x = 1
def f():
y = x
x = 2
return x + y
print x
print f()
print x
but python is not going to look up the variable out of function scope , and it results in UnboundLocalError: local variable 'x' referenced before assignment . I am not trying to modify the value of global variable , i just want to use it when i do y=x.
On the other hand if i just use it in return statment , it works as expected:
x = 1
def f():
return x
print x
print f()
Can some one explain it why?
you have to specify global x in your function if you want to modify your value,
however it's not mandatory for just reading the value:
x = 1
def f():
global x
y = x
x = 2
return x + y
print x
print f()
print x
outputs
1
3
2

Categories