首页 > 解决方案 > python中的形状区域

问题描述

所以我有一个名为 the_rectangle 的函数,我运行了两次来创建两个矩形。但是,我希望 python 找出每个矩形的面积,并通过打印(“较大的矩形的面积是:”)然后打印(“较小的矩形的面积是:”)来确定哪个更大。我还希望它使用参数宽度和长度来查找每个区域的值。这可能吗?

import turtle
import math


def the_rectangle(width, length, color):
    turtle.color(color)
    turtle.begin_fill()
    turtle.forward(width)
    turtle.left(90)
    turtle.forward(length)
    turtle.left(90)
    turtle.forward(width)
    turtle.left(90)
    turtle.forward(length)
    turtle.left(90)
    turtle.end_fill()

def main():
    the_rectangle(200, 100, "red")
    turtle.penup()
    turtle.forward(300)
    turtle.pendown()
    the_rectangle(100, 250, "yellow")

main()

标签: pythonturtle-graphics

解决方案


有很多方法可以完成您想要的,但对现有代码的最简单修改可能是让“the_rectangle”返回该区域。您需要获取返回值并计算最大/最小面积。

如果你想让这个程序成为一个更大规模的程序,你需要去创建类,就像其他答案中提到的那样。

import turtle
import math


def the_rectangle(width, length, color):
    # This function draws a rectangle and returns the area
    turtle.color(color)
    turtle.begin_fill()
    turtle.forward(width)
    turtle.left(90)
    turtle.forward(length)
    turtle.left(90)
    turtle.forward(width)
    turtle.left(90)
    turtle.forward(length)
    turtle.left(90)
    turtle.end_fill()
    return width*length

def main():
    area_1 = the_rectangle(200, 100, "red")
    turtle.penup()
    turtle.forward(300)
    turtle.pendown()
    area_2 = the_rectangle(100, 250, "yellow")
    print("Largest rectangle is " + str(max(area_1,area_2)))
    print("Smallest rectangle is " + str(min(area_1,area_2)))

main()

推荐阅读