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
3
  • 1
    Fix your indentation please. Commented Oct 5, 2017 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. Commented Oct 5, 2017 at 14:38
  • 1
    Possible duplicate of How to return a value from a function? Commented Oct 5, 2017 at 14:41

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

Comments

0

You can also do :

print "The answer is: " + str(area(3))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.