Why python not printing 100 and 1000 [duplicate] - python

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 5 years ago.
x=100
def fun2():
print x
x=10000
print x
fun2()
The above program showing local variable x reference before assignment. Why it is not printing
100
10000

x in the function is a local variable and can't access the other local variable you define first because they are in different scope.
Add global x to the start of your function or define x inside the function.

You appear to not know about variable scoping.
The variable x does not exist in the function scope.
You have to place global x before your print statement in order to access the global variable x.
x = 1 # Global x
def f():
x = 2 # function-local x
print(x) # prints 2
f()
print(x) # prints 1 because it uses the global x which remains unchanged

If you want that to work you need to specify inside the function that the x variable you are using is the one in the global scope by using the global keyword.
x=100
def fun2():
# Add this line
global x
print x
x=10000
print x
fun2()

Below code will print the value of x -> 100, as it is there in main scope #samba, but when you change the value of it doesn't work that way as it is not defined in the function.
x = 100
def fun2():
print(x)
fun2()
This doesn't work as the same way:
x = 100
def fun2():
print(x)
x = 1000
print(x)
fun2()
and through error:
UnboundLocalError: local variable 'x' referenced before assignment
x is a local variable and not initialised in function fun2().
You need to understand variable scoping here, Please check Global and Local variable scope
If you want to use it globally use global keyword in your function.

Because u assigned variable before function.
Just try this
def fun2():
x=100
print x
x=10000
print x
fun2()
It will output 100 and 1000

Related

Accessing variable in a function without calling it in Python

Here is my code
def function():
global x
x = 5
print (x)
How can I access the local variable x inside the function without calling the function itself?
It's not possible. A variable inside a function will only be after the function is called, else it is non-existent. Look into how locallocal,non-local, and global variables work.
def function():
global x
x = 5
print(x)
function()
else you should just put x outside the function().
Just put x = 5 outside the function

nonlocal statement got checked without running the function in python [duplicate]

This question already has answers here:
When is the existence of nonlocal variables checked?
(2 answers)
Closed 4 years ago.
previously I thought that when we define a function, the function can be wrong, but python will not check it until it got executed:
x = 100
def f():
x = 1/0
return x
print(x)
# >>> 100
however, when I was learning the nonlocal statement
x = 100
def f():
def g():
nonlocal x
x = x * 99
return x
return g
print(x)
# >>> SyntaxError: no binding for nonlocal 'x' found
It got checked out even if the function is not executed.
Is there anywhere I can find the official explanation for this?
Additional for variable bounding situation:
x = 100
def f():
global x
global xx
x = 99
return x
print(f())
# >>> 99
print(x)
# >>> 99
it seemed totally fine, if I global some variable that does not exist at all?
And it doesn't even bring any error even if I execute this function?
this part is moved to a new individual question:
Why am I able to global a non-existing varlable in python
The nonlocal checks the nearest enclosing scope, excluding globals (that is, module level variables). That is, your f() function should declare a x for it to work, as nonlocal can't see the global x = 100 variable.
See https://docs.python.org/3/reference/simple_stmts.html#the-global-statement.
As to why the error is raised without running the function, it is because the variable names are bound at compile-time, so it doesn't matter that you don't use this function at all. See
https://docs.python.org/3/reference/executionmodel.html#resolution-of-names
However, global has different behaviour. Just like nonlocal if the global x already exists, it is used instead of the local one. However, if it doesn't, it means "if I create a variable named x, create it on the global scope, instead of the function scope". So, in your example
x = 100
def f():
global x
global xx
x = 99
xx = 123
return x
print(f()) # 99
print(x) # 99
print(xx) # 123
a xx variable has appeared in the global namespace. It is only a hint to the compiler though, so if you declared global xx without assigning it, and try to print(xx) later, you still get a NameError for using an undefined variable

How do global and local variables behave in this case? [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
Closed 6 months ago.
This is saved in my file function_local.py:
x = 50
def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)
func(x)
print('x is still', x)
Output:
$ python function_local.py
x is 50
Changed local x to 2
x is still 50
Question: When we print the first line inside the Function, why does it print out 50, not 2? Even if it is said, in the function, that x = 2?
In case you assign to a variable name (that wasn't declared global or nonlocal) in a function or use the variable name in the argument list of the function the variable name will become part of the function.
In that case you could've used any variable name inside the function because it will always refer to the local variable that was passed in:
x = 50
def func(another_x):
print('local x =', another_x)
another_x = 2
print('local x =', another_x)
return another_x
print('global x =', x)
x = func(x) # note that I assigned the returned value to "x" to make the change visible outside
print('global x =', x)
More explanation
I'm going to try to show what I meant earlier when I said that x with "will become part of the function".
The __code__.co_varnames of a function holds the list of local variable names of the function. So let's see what happens in a few cases:
If it's part of the signature:
def func(x): # the name "x" is part of the argument list
pass
print(func.__code__.co_varnames)
# ('x',)
If you assign to the variable (anywhere in the function):
def func():
x = 2 # assignment to name "x" inside the function
print(func.__code__.co_varnames)
# ('x',)
If you only access the variable name:
def func():
print(x)
print(func.__code__.co_varnames)
# ()
In this case it will actually look up the variable name in the outer scopes because the variable name x isn't part of the functions varnames!
I can understand how this could confuse you because just by adding a x=<whatever> anywhere in the function will make it part of the function:
def func():
print(x) # access
x = 2 # assignment
print(func.__code__.co_varnames)
# ('x',)
In that case it won't look up the variable x from the outer scope because it's part of the function now and you'll get a tell-tale Exception (because even though x is part of the function it isn't assigned to yet):
>>> func()
UnboundLocalError: local variable 'x' referenced before assignment
Obviously, it would work if you access it after assigning to it:
def func():
x = 2 # assignment
print(x) # access
Or if you pass it in when you call the function:
def func(x): # x will be passed in
print(x) # access
Another important point about local variable names is that you can't set variables from outer scopes, except when you tell Python to explicitly not make x part of the local variable names, for example with global or nonlocal:
def func():
global x # or "nonlocal x"
print(x)
x = 2
print(func.__code__.co_varnames)
# ()
This will actually overwrite what the global (or nonlocal) variable name x refers to when you call func()!
In your function
def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)
x is not a global variable; it is a local variable due to the assignment on the second line of the body. If you are going to assign to a global variable, it must be explicitly declared as such:
def func(x):
global x
print('x is', x)
x = 2
print('Changed local x to', x)
(Note: I missed that x is actually a function parameter. See https://nedbatchelder.com/text/names.html for an explanation of assignments to local names do not affect global names.)
this could be easily understand by this.
x = 50
def func(x):
print "Local variables: "+str(locals())
print('x is', x)
x = 2
print "Local variables: "+str(locals())
print('Changed local x to', x)
func(x)
print('x is still', x)
and the output
Local variables: {'x': 50}
'x is', 50
Local variables: {'x': 2}
'Changed local x to', 2
'x is still', 50
however if you want to access the x from outer scope after defining the x in func there is a way, I am not sure if it would create a issue or not though.
def func(x):
x = 2
print "local x == %s" % x
print "global x == %s" % globals().get('x')
func(x)
print "x is still %s" % x
Following will be output of the run.
local x == 2
global x == 50
x is still 50

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

Global Variables in functions with if statements

Okay, I am currently doing a project to make a blackjack game in python and I'm having some trouble. One of my issues is I dont know when to define a variable as global, specifically in functions with if statements. If I have a global variable outside the if statement, do I have to claim that the variable is global within the if statement as well? For example:
x = 5
def add():
global x <--- ?
x += 1
if x == 7:
global x <--- ?
x = 5
I'm pretty sure I need the "global x" at the 1st question mark, but what about at the second question mark? Would I still need to put a "global x" within my if statement if I wanted my if statement to update a global variable? Or does the global x at the beginning of the function make the x's inside the if statement global? Also, if I wanted to return x here, where should I do it?
Only one global statement is enough.
From docs:
The global statement is a declaration which holds for the entire
current code block.
x = 5
def add():
global x
x += 1
if x == 7:
x = 5
Also, if I wanted to return x here, where should I do it?
If you're using global in your function then the return x must come after the global x statement, if you didn't use any global statement and also didn't define any local variable x then you can return x anywhere in the function.
If you've defined a local variable x then return x must come after the definition.

Categories