为什么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")
答案 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件事:
#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
是一个局部变量,但您在函数外部使用它。事实上,你实际上从未调用任何函数。