Reputation: 3
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
Upvotes: 0
Views: 327
Reputation: 6581
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))
Upvotes: 1