python - 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()
解决方案
有很多方法可以完成您想要的,但对现有代码的最简单修改可能是让“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()
推荐阅读
- flutter - 初始化的数据库仍然返回 null [Flutter, sqflite]
- python - Python - 使用基于字典查找的参数调用函数
- react-native - 使用嵌套异步的 React-Native 无法正常工作
- java - Spring JPA 规范和 JSONB 字符串数组 [Postgres]
- kotlin - Android (Kotlin) WebRTC - “解析失败:”。原因:无效的 SDP 行“
- javascript - 是否可以在 Angular Element 中包含一个 img src?
- c# - 读取串口数据而不丢失任何数据和解析
- python - 异常是未安装 Google Speech Recognition API 的原因吗?
- linkedin - 如何从 Linkedin 应用程序中删除权限
- mongodb - MongoDB。使用 admin 数据库创建用户与其他数据库