使用Python绘制正方形可以通过多种方式实现,以下是使用`turtle`模块和`matplotlib`库的两种方法:
使用`turtle`模块绘制正方形
import turtle创建画布和画笔canvas = turtle.Screen()pen = turtle.Turtle()绘制正方形for _ in range(4):pen.forward(100) 向前移动100个像素pen.right(90) 向右转90度结束绘制turtle.done()
使用`matplotlib`库绘制正方形

import matplotlib.pyplot as pltimport numpy as np创建画布和轴fig, ax = plt.subplots()绘制正方形ax.plot([0, 1, 1, 0], [0, 0, 1, 1], 'k-', linewidth=2) 黑色边框ax.plot([0.5, 0.5, 0.5, 0.5], [0.5, 1, 1, 0.5], 'r-', linewidth=2) 红色分割线设置轴的范围ax.set_xlim(0, 1)ax.set_ylim(0, 1)设置轴的比例为相等ax.set_aspect('equal')显示图形plt.show()
以上代码分别展示了如何使用`turtle`模块和`matplotlib`库来绘制正方形。`turtle`模块适合初学者,而`matplotlib`库则提供了更高级的绘图功能。您可以根据需要选择使用
