返回

理解Python中的draw_square()函数及其使用方法

闲谈




Python 中的函数是一种方便的方式,可以将几行代码打包成一个可以调用的简单。当关键词被调用时,函数中包含的所有代码都会运行。在涵盖循环和 Turtle 的教程中,我们用一个循环来画一个正方形。使用 draw_square() 函数,您可以通过指定正方形的大小和位置来轻松地绘制正方形。

import turtle

def draw_square(size, x, y):
  """
  Draws a square using the Turtle graphics library.

  Args:
    size: The size of the square in pixels.
    x: The x-coordinate of the center of the square.
    y: The y-coordinate of the center of the square.
  """

  # Move the turtle to the center of the square.
  turtle.penup()
  turtle.goto(x, y)
  turtle.pendown()

  # Draw the square.
  for i in range(4):
    turtle.forward(size)
    turtle.right(90)

# Draw a square with a size of 100 pixels, centered at (0, 0).
draw_square(100, 0, 0)

# Draw a square with a size of 50 pixels, centered at (50, 50).
draw_square(50, 50, 50)

draw_square() 函数接受三个参数:

  • size: 正方形的大小,以像素为单位。
  • x: 正方形中心点的 x 坐标。
  • y: 正方形中心点的 y 坐标。

该函数首先将画笔移动到正方形的中心点。然后,它使用一个循环来绘制正方形。循环将重复四次,每次都会向前移动 size 像素,然后向右转 90 度。这将创建正方形的四个边。

您可以使用 draw_square() 函数来绘制不同大小和位置的正方形。只需在调用函数时更改参数即可。例如,以下代码将绘制一个大小为 100 像素,中心点位于 (0, 0) 的正方形:

draw_square(100, 0, 0)

以下代码将绘制一个大小为 50 像素,中心点位于 (50, 50) 的正方形:

draw_square(50, 50, 50)

draw_square() 函数是一个非常有用的工具,可以用于创建各种图形。它很容易使用,而且可以帮助您快速轻松地绘制正方形。