0

I'm trying to write a code but there's something wrong. I'm not able to print the result of a function. Here is a mini example of what's wrong in my code:

import math

def area(r):
    "It will display the area of a circle with radius r"
    A = math.pi*r**2
    print("The answer is:", str(A))
    return A

area(3)

print(str(A)) # This line is not working

# NameError: name 'A' is not defined
Yam Mesicka
  • 6,243
  • 7
  • 45
  • 64
  • 1
    Fix your indentation please. – Aran-Fey Oct 05 '17 at 14:35
  • Also, you're not assigning the return value of `area(3)` anywhere. The `return A` statement doesn't automagically create an `A` variable when the function is called. – Aran-Fey Oct 05 '17 at 14:38
  • 1
    Possible duplicate of [How to return a value from a function?](https://stackoverflow.com/questions/19080943/how-to-return-a-value-from-a-function) – Aran-Fey Oct 05 '17 at 14:41

2 Answers2

1

When you define a variable within a function, it is defined only within that function and does not leak out to the rest of the program. That is why A is not accessible outside of the area function.

Using return, you are able to send values back to the place where the function was called from.

The last two lines should look like:

total_area = area(3)

print(str(total_area))
Yam Mesicka
  • 6,243
  • 7
  • 45
  • 64
0

You can also do :

print "The answer is: " + str(area(3))
Rekoc
  • 438
  • 6
  • 17