Python - 为什么外围未定义?

时间:2013-07-04 03:03:42

标签: python syntax

为什么Python报告变量perimeter未定义?

#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") 

3 个答案:

答案 0 :(得分:2)

你还没有调用你的功能;你只定义了它们。要调用它们,您必须执行rectanglePerimeter(length, width)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") 

答案 1 :(得分:1)

2件事:

  1. 您应该将函数调用的结果存储到变量中。
  2. 你可以用else替换最后一个if语句(因为第三种情况只有在相等时才会发生)
  3. #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") 
    

答案 2 :(得分:0)

perimeter是一个局部变量,但您在函数外部使用它。事实上,你实际上从未调用任何函数。