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 3 years ago.
I am relatively new to python and I can't understand why does this throws an error.
ar=''
def decToBin(no):
while(no>0):
ar=ar+str(no%2)
no=no//2
print(ar[::-1])
decToBin(4)
code that works
def decToBin(no):
ar=''
while(no>0):
ar=ar+str(no%2)
no=no//2
print(ar[::-1])
decToBin(4)
The scope of the "ar" variable is supposed to be global and should be accessible inside the function. Can anyone explain why the former isn't working?
The issue is this line:
ar=ar+str(no%2)
You are referencing it, before it has been assigned.
Try this instead:
ar = ''
def decToBin(no):
while(no>0):
#ar=ar+str(no%2)
no=no//2
print((ar+str(no%2))[::-1])
decToBin(4)
Changing decimal to binary is easy with numpy:
import numpy as np
np.binary_repr(4, width=None)
Related
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 12 days ago.
Im playing around with functions and I never was able to understand why I couldn't change a variable. It always gives me an error.
Iv'e tried googling it but nothing really worked. Could someone help me out with this?
x = 1
def run():
print(x)
x += 1
run()
Since you are assigning to x, you need to declare it as global.
def run():
global x
print(x)
x += 1
Otherwise, the assignment makes it a local variable, one you try to print before assigning to it (and one that isn't initialized before you try to increment it).
This question already has answers here:
How to get local variables updated, when using the `exec` call?
(3 answers)
Closed 1 year ago.
Given a string (e.g. "lista=[1,2,3]") I would like to be able to use the variable lista.
exec() does the work outside a function, but when used inside a function the variables cannot be used in that same function. I guess it has something to do with local and global variables but I don't really understand the problem.
For example,
def funcion(texto):
exec(texto)
print(lista)
funcion("lista = [3,4,5]")
Gives the error: NameError: name 'lista' is not defined.
add globals
def funcion(texto):
exec(texto, globals())
print(lista)
funcion("lista = [3,4,5]")
This question already has answers here:
How do I forward-declare a function to avoid `NameError`s for functions defined later?
(17 answers)
Closed 3 years ago.
Simple python script is giving error, what is wrong?
var ="first variable"
myfun(var)
def myfun(var):
print(var)
Error -> NameError: name 'myfun' is not defined
This thing is quite obvious though. Python reads the code line by line and not like C.
Just switch your two blocks i.e. definition of function and calling it.
var ="first variable"
def myfun(var):
print(var)
myfun(var)
This should be good to go.
When python interpreter sees the statement myfun(var), the name myfun is not defined yet. You need to move this line after your function definition.
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 7 years ago.
I'm a bit confused as to how Python's variable scope system works. Say I have situation like this:
a = 10
def test():
print(a)
Then everything works just as I expect. Python first looks for a local variable a, fails to find it and then searches for a global variable.
However, in a situation like this:
a = 10
def test():
print(a)
a += 1
print(a)
Python throws an UnboundLocalError exception, apparently originating from line 3 (print(a)). To me it seems that at least to this line nothing has changed, and I don't understand why there is an exception anyway.
Since python does not have variable declarations, every variable assignment inside the scope of a function is considered local. So, you always have to specify that that variable is a global one:
a = 10
def test():
global a
print(a)
a += 1
print(a)
test()
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 8 years ago.
I have found a similar question Python variable scope error. It's related to immutable variable. But when I test mutable variable, I don't know how Python interpreter decides the scope of the variable.
Here's my sample code:
def test_immutable():
a = 1
b = 2
def _test():
print(a)
print(b)
a += 1
print(a)
_test()
def test_mutable():
_dict = {}
def _test():
print(_test.__dict__)
_dict['name'] = 'flyer'
print('in _test: {0}'.format(_dict['name']))
_test()
print(_dict['name'])
if __name__ == '__main__':
# test_immutable() # throw exception
test_mutable() # it's ok
Immutable vs mutable has nothing to do with variable scoping. Variables are just names, and always work the same way. Scoping is even decided at compile time, long before Python knows what you're going to assign to them.
The difference between your two functions is that the first one assigns directly to a with the += operator, which causes a to become a local. The second one assigns to a key inside _dict, which ultimately calls a method on the dict object, and doesn't affect the variable's scoping.