#!/usr/bin/python3
def func():
a = 1
print(a+12)
print(a)
The result is:
NameError: name 'a' is not defined
Is it possible to use a outside the function?
#!/usr/bin/python3
def func():
a = 1
print(a+12)
print(a)
The result is:
NameError: name 'a' is not defined
Is it possible to use a outside the function?
I don't think you can because the scope of the variable 'a' is limited within the function func(). You can call the 'a' variable outside the function if you defined it outside. If you are beginner in python(like me) use this. It helped me
PS: I may be wrong as I'm a beginner in python as well
In python the scope is a function, or class body, or module; whenever you have the assignment statement foo = bar
, it creates a new variable (name) in the scope where the assignment statement is located (by default).
A variable that is set in an outer scope is readable within an inner scope:
a = 5
def do_print():
print(a)
do_print()
A variable that is set in an inner scope cannot be seen in outer scope. Notice that your code does not even ever set the variable as that line is not ever run.
def func():
a = 1 # this line is not ever run, unless the function is called
print(a + 12)
print(a)
To make something like you wanted, a variable set within a function, you can try this:
a = 0
print(a)
def func():
global a # when we use a, we mean the variable
# defined 4 lines above
a = 1
print(a + 12)
func() # call the function
print(a)
You can pass a value along into a higher scope by using the return
statement.
def func():
a = 1
print(a+12)
return a
a = func()
print(a)
Result:
13
1
Note that the value isn't bound to the name that the variable had inside the function. You can assign it to whatever you want, or use it directly in another expression.
def func():
a = 1
print(a+12)
return a
func()
print(a) #this will not work. `a` is not bound to anything in this scope.
x = func()
print(x) #this will work
print(func()) #this also works