python-Day3

piter 发布于 2025-04-12 144 次阅读 532 字


AI 摘要

在今天的学习中,我们深入探讨了 Python 中函数调用的奥秘,特别是如何通过精确的参数设置来绘制美丽的图形。通过编写简单的函数,我们能够创造出正方形和矩形,甚至以间隔排列多个图形,让画布上生动起来!想知道如何在你的程序中利用这些技巧吗?让我们一起探索如何通过编程点亮创造力的火花!明天见!

学了点函数调用

customer.py

# coding: utf-8

from turtle import *


# 1
# 实现函数, 用于画一个正方形, 边长由参数提供
# 参数 x, y 是正方形左上角坐标
# 参数 l 是正方行边长
# 函数声明如下
# square(x, y, l)

def square(x, y, l):
    penup()
    goto(x, y)
    pendown()
    setheading(0)
    i = 0
    while i < 4:
        forward(l)
        right(90)
        i = i + 1


# 2
# 实现函数, 用于画一个矩形, 长宽由参数提供
# 参数 x, y 是左上角坐标
# 参数 w, h 是长宽
# 函数声明如下
# rect(x, y, w, h)

def rect(x, y, w, h):
    penup()
    goto(x,y)
    pendown()
    setheading(0)
    i = 0
    while i < 2:
        forward(w)
        right(90)
        forward(h)
        right(90)
        i = i + 1

# 3
# 画一排正方形, 一共 5 个
# 从 0 0 点开始, 边长为 30, 正方形之间间隔为 0
# 函数声明如下
# square5()
# 提示 根据资料中的循环例子, 计算每个正方形的坐标

def square5():
    i = 0
    x = 0
    while i < 5:
        square(x,0,30)
        x = x + 30
        i = i + 1


# 4
# 画一排正方形, 一共 5 个
# 从 0 0 点开始, 边长为 30, 正方形之间间隔为 10 像素
# 函数声明如下
# square5_10()

def square5_10():
    i = 0
    x = 0
    while i < 5:
        square(x,0,30)
        x = x + 40
        i = i + 1

# 5
# 实现函数, 画一排正方形, 有如下参数
# x, y 是第一个正方形左上角坐标
# n 是正方形的个数
# space 是两个正方形之间的间距
# len 是正方形的边长
# square_line(x, y, n, space, len)

def square_line(x,y,n,space,length):
    i = 0
    while i < n:
        square(x,y,length)
        x = x + length + space
        i = i + 1

main.py

# coding: utf-8

# 这个文件的代码不要做任何修改
# 这个文件的代码不要做任何修改
# 这个文件的代码不要做任何修改

from turtle import *
from customer import action


def clean_screen():
    clear()
    penup()
    home()
    pendown()
    showturtle()


def close():
    bye()


def main():
    setup(width=800, height=600, startx=0, starty=0)
    title('按 S 开始绘图,按 D 清除界面,按 Esc 关闭')
    showturtle()
    speed(2)
    onkeyrelease(action, 's')
    onkeyrelease(clean_screen, 'd')
    onkeyrelease(close, 'Escape')
    listen()
    done()


if __name__ == '__main__':
    main()

学习了基本的定义函数和相关调用知识,比如:

> if __name__ == '__main__':
      main()

明天见!

  • reward_image1
永远不要因为需要大量时间才能完成,就放弃梦想,时间怎么样都会过去的
最后更新于 2025-04-12