1

Hello all…a newbie question if you don’t mind.

Like below:

def plus_it(a, b):
    result = a + b
    if result == 0:
        aa = '0'
        #print aa    an option here
    else:
        aa = 'the result is ' + str(result)
        #print aa    an option here

plus_it(5, 6)
print aa

I can add on print ‘aa’ lines inside the function. However if I want to use the ‘aa’ outside the function like above, it gives an error:

NameError: name 'aa' is not defined

How can I use the ‘aa’ outside the function?

Thanks.

Mark K
  • 8,767
  • 14
  • 58
  • 118

2 Answers2

1

Use the return statement and assign the returned value to aa:

def plus_it(a, b):
    result = a + b
    if result == 0:
        return '0'
    else:
        return 'the result is ' + str(result)

aa = plus_it(5, 6)
print aa
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

You can't use aa outside the function. The variable aa has a local scope. You have two options:

  • Return a value from your function and use it outside
  • Use a global variable
aa = 0
def plus_it(a, b):
    global aa
    aa = 'value'
Deck
  • 1,969
  • 4
  • 20
  • 41