使用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 plt
import 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`库则提供了更高级的绘图功能。您可以根据需要选择使用