1

This here is my code:

def Area():
    area = pi * radius * radius
    pi = 3.14
    radius = diameter * 2

def cost():
    diameter = eval(input("diamater: "))
    print ("Area is", area)
cost()

it says area is not defined but I have a variable called area!

Average kid
  • 6,099
  • 6
  • 20
  • 17

4 Answers4

6

area is a local variable in a function, that means that outside of that function, you can't access it. You should read up on scoping and functions. The best solution here is to return values from your functions, and pass arguments into others.

You seem to lack an understanding of how the code is evaluated. Code is executed as a series of statements in order, one after the other. Variables can only be used once they have been defined. In Area(), you are defining your variables after you are attempting to use them. This doesn't make sense.

Also note that eval() is a bad way of getting a number from a string (it is slow, not designed for the purpose, and allows arbitrary code execution), use int() instead.

Also note that PEP-8 recommends keeping CapWords for classes, and using lowercase_with_underscores for function names, so Area() should probably be area(). This will help keep your code consistent and readable.

Gareth Latty
  • 82,334
  • 16
  • 175
  • 177
0

You should:

  1. make Area() return area;
  2. call Area() from cost(), making appropriate use of its result.

Finally, the ordering of statements within Area() looks very odd indeed.

NPE
  • 464,258
  • 100
  • 912
  • 987
0

Variables are localized to the scope of the method. If you want to use the value from the method, return it:

def area(diameter=1):
    pi = 3.14
    radius = diameter * 2
    area = pi * radius * radius
    return area

# Calling the value
def cost():
    diameter = eval(input("diamater: "))
    print ("Area is", area(diameter))

It's also worth mentioning that in your original code:

  • diameter isn't defined anywhere. Your intent is to pass it into the method; I've provided that hint here.
  • The order of your variables is incorrect. They must be declared before they are used.
Makoto
  • 100,191
  • 27
  • 181
  • 221
0

I would suggest to take a look at this course https://class.coursera.org/programming1-2012-001/class/index .

Moj
  • 5,435
  • 2
  • 21
  • 34