0

Why is Python reporting that the variable perimeter is undefined?

#The first function will accept the length and width of a rectangle as its two parameters and return the rectangles perimeter
length=float(input("What is the length of your rectangle?"))
width=float(input("What is the width of your rectangle?"))
def rectanglePerimeter(length,width): #the parameter limits , it will accept the length and the width 
    perimeter= (2*length) + (2*width ) #here we implement the equation for the rectangles perimeter 
    return perimeter #return the result 
def rectangleArea(length,width):
    area= length*width 
    return area 
if perimeter> area:
    print ("the perimeter is larger than the area")
elif perimeter<area:
    print ("the area is larger than the perimeter")
    if perimeter == area:
        print ("the area and the perimeter are equal") 
4

3 回答 3

2

你还没有调用你的函数;你只定义了它们。要调用它们,您必须执行类似rectanglePerimeter(length, width)or的操作rectangleArea(length, width)

perimeter = rectanglePerimeter(length, width) # Where length and width are our inputs
area = rectangleArea(length, width) # Where once again length and width are our inputs

此外,您的 if/elif 语句似乎有点偏离:

if perimeter > area:
    print ("the perimeter is larger than the area")
elif perimeter < area:
    print ("the area is larger than the perimeter")
elif perimeter == area: # This should not be nested, and it should be another elif. Infact, you could probably put an else: here.
    print ("the area and the perimeter are equal") 
于 2013-07-04T03:10:06.930 回答
1

2件事:

  1. 您应该将函数调用的结果存储到变量中。
  2. 您可以用 else 替换最后一个 if 语句(因为第三种情况仅在它们相等时才会发生)
#The first function will accept the length and width of a rectangle as its two parameters and return the rectangles perimeter
length=float(input("What is the length of your rectangle?"))
width=float(input("What is the width of your rectangle?"))

def rectanglePerimeter(length,width): #the parameter limits , it will accept the length and the width 
    perimeter= (2*length) + (2*width ) #here we implement the equation for the rectangles perimeter 
    return perimeter #return the result 

def rectangleArea(length,width):
    area= length*width 
    return area 

# need to call the functions, and store the results into variables here:
perimeter = rectanglePerimeter(length, width)
area = rectangleArea(length, width)

if perimeter> area:
    print ("the perimeter is larger than the area")
elif perimeter<area:
    print ("the area is larger than the perimeter")
else: # At this point, perimeter == area
    print ("the area and the perimeter are equal") 
于 2013-07-04T03:08:11.927 回答
0

perimeter是一个局部变量,但您在函数外部使用它。事实上,你从来没有真正调用过你的任何函数。

于 2013-07-04T03:05:55.357 回答