0
#!/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?

Ed Dabbah
  • 79
  • 1
  • 3
  • I think you may need to read a little bit more about "scope" in python. a is declared within the scope of func() so it cannot be seen outside of that scope. – Doug Morrow Aug 19 '13 at 19:35
  • Can I do it with a built in function or something like that is it possible – Ed Dabbah Aug 19 '13 at 20:19
  • If you want to access **a** outside the scope of **func()** it simply needs to be declared outside the scope of **func()**. If this isn't making sense then I seriously recommend reading some python tutorials. Just about any tutorial will teach you what you want to know about scope. – Doug Morrow Aug 19 '13 at 20:27
  • I am discovering, why he needed this at all :), Your question is PUBLIC, Subterfuge made it PROTECTED, but your demand is PRIVATE – Notepad Aug 20 '13 at 16:21
  • possible duplicate of [Do you use the "global" statement in Python?](http://stackoverflow.com/questions/146557/do-you-use-the-global-statement-in-python) – Dima Tisnek May 07 '14 at 09:57

3 Answers3

0

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

user9517536248
  • 355
  • 5
  • 24
0

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)
0

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
Kevin
  • 74,910
  • 12
  • 133
  • 166