Python:turtle程序语法元素分析

库引用与import

库引用:扩充Python程序功能的方式,使用import保留字完成,采用 a . b()编码风格,格式为:import <库名> <库名>.<函数名>(<函数参数>)
为避免每次使用库中的函数都要写一遍库名,可以使用from和import保留字共同完成,**格式为:
**from <库名> import <函数名>
或者from <库名> import *,
这样写了之后,就可以不写库名,而直接用函数名加参数的方式。

from turtle import*
penup()
fd(-250)
pendown()
pensize(25)
pencolor("purple")
seth(-40)
for i in range(4):
    circle(40,80)
    circle(-40,80)
circle(40,80/2)
fd(40)
circle(16,180)
fd(40 * 2/3)

对turtle中的已有函数,直接使用函数名就可以完成相关功能。
两种方法各有优缺点:
import <库名>
<库名>.<函数名>(<函数参数>)

这种方法避免了函数重名的问题,因为<库名>.<函数名>就相当于新的函数名。
from <库名> import <函数名>
from <库名> import

<函数名>(<函数参数>)
*
库中的函数名字可能与用户自定义的函数名相同,从而出错。如果程序中import很多库,就用第一种形式。
另外的库引用方法
使用import和as保留字共同完成
格式:import <库名> as <库别名>
<库别名>.<函数名>(<函数参数>)
给调用的外部库关联一个更短、更适合自己的名字。
例如:

import turtle as t
t.penup()
t.fd(-250)
t.pendown()
t.pensize(25)
t.pencolor("purple")
t.seth(-40)
for i in range(4):
    t.circle(40,80)
    t.circle(-40,80)
t.circle(40,80/2)
t.fd(40)
t.circle(16,180)
t.fd(40 * 2/3)
t.done()

这种方法很建议用

turtle画笔控制函数

  • penup()
  • pendown()
  • pensize()
  • pencolor()
    penup()和pendown()画笔操作后一直有效,所以控制函数一般成对出现。
  • turtle.penup() 别名 turtle.pu(),抬起画笔
  • turtle.pendown() 别名 turtle.pd(),落下画笔
  • turtle.pensize(width) 别名 turtle.width(width),画笔宽度
  • turtle.pencolor(color) color 为颜色字符串或r,g,b值,画笔颜色。pencolor(color)的color参数可以有三种形式:1.颜色字符串:turtle.pencolor(“purple”) 2.RGB的小数值:turtle.pencolor(0.63,0.13,0.94) 3.RGB的元组值:turtle.pencolor((0.63,0.13,0.94))

turtle运动控制函数

  • turtle.fd()
  • turtle.circle()
    运动控制函数控制海龟行进:走直线&走曲线
  • turtle.forward(d) 别名 turtle.fd(d),向前行进,(d)为行进距离,可以为负数
  • turtle.circle(r,extent=None),含义是根据半径r绘制一个extent角度的弧形。即r:默认圆心在海龟左侧r距离的位置,当r为负数时圆心在海龟右侧。extent:绘制角度,默认是360度整圆。例如:turtle.circle(100)和turtle.circle(-100,90)

turtle方向控制函数

控制海龟面对的方向:绝对角度&海龟角度

  • turtle.setheading(angle) 别名 turtle.seth(angle),改变行进方向,angle,为改变的行进方向。例如turtle.seth(45)表示把海龟的方向转为绝对坐标系中的45度方向。turtle.seth(-135)同理。
  • turtle.left(angle) 海龟向左转
  • turtle.right(angle) 海龟向右转
  • angle:在海龟当前行进方向上旋转的角度
  • 要注意,方向控制函数仅仅改变方向

循环语句与range函数

  • 格式为:for <变量> in range (<参数>)
    <被循环执行的语句>
  • range的参数即为循环的次数
  • <变量>表示每次循环的计数,0到<次数>-1
    例如:
for i in range(5):
    print(i)
for i in range(5):
    print("Hello:",i)

输出为:

Hello: 0
Hello: 1
Hello: 2
Hello: 3
Hello: 4

print函数中的逗号在输出时变为空格。

  • range()函数产生循环计数序列
  • 第一种格式为:range(N),产生0到N-1的整数序列,共N个
  • 第二种格式为:range(M,N),产生从M开始到N-1的整数序列,共N-M个
发布了28 篇原创文章 · 获赞 1 · 访问量 604

猜你喜欢

转载自blog.csdn.net/qq_44384577/article/details/104405330