-4

If I had a function that I made:

def a():
    n = 2*2

How could I access n out of the function without calling a?

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
J. Doe
  • 1,475
  • 2
  • 9
  • 17
  • A [related question](https://stackoverflow.com/q/9059349) comes to mind, although that's about accessing a variable inside a function when you _do_ call the function, so it's not really a duplicate. – David Z Jul 31 '18 at 01:30
  • Why would you want to? – AChampion Jul 31 '18 at 01:35
  • Have you looked at the answers to [this question](https://stackoverflow.com/questions/19326004/access-a-function-variable-outside-the-function-without-using-global)? – martineau Jul 31 '18 at 02:17

2 Answers2

3

You cannot. You will need to define the variable outside of the function, or call the function and return it.

sundance
  • 2,905
  • 4
  • 21
  • 31
0

You need to return it, so do:

def a():
    n = 2*2
    return n
print(a())

Output:

4

You can also do print, but return is better, check this: What is the formal difference between "print" and "return"?

U13-Forward
  • 69,221
  • 14
  • 89
  • 114