Python_levl2.3函数
一、引入
**之前画过一朵很复杂的太阳花,如果想在另一个地方画怎么办?
1)复制一遍代码(麻烦+不高大上)
2)魔法技能卷轴(封装+调用)[函数]
二、函数
**魔法技能卷轴(先把功能封装+需要时调用)
1)使用过的函数:
pencolor() range()#范围
left() pop()#用于从列表或字典中移除,并返回指定元素
right() print()
2)自己定义函数:
def 函数名 (参数列表) :
函数体
[ 6件套:]
def:define,定义
函数名:命名规则,可以字母、数字、下划线组成,但不能以数字开头。
例如:
def 9_name(): #错误(数字开头,[X错])
def pencolor(): #正确(最好表达出函数的功能)
参数作用:在函数定义/调用,过程中使用的变量,用于传递数据+控制函数的行为。
(灵活+可读性强+易于维护的代码)
函数体:缩进标准格式,4个字符(与if语句,for循环语句一样)
** 使用Tab键进行多行缩进
1)缩进,按下Tab键,向右(1个制表符宽度)
2)减少缩进,按下Shift + Tab组合键,向左
三、函数的创建+封装+调用
1.创建函数
def function():
#函数体
pass #pass 跳过
print("hello")
**pass:占位符,不影响函数调用。
2.函数封装+调用:(太阳花代码)
1)太阳花代码:
import turtle
turtle.speed(0)
#画笔移动到花的底部
turtle.up()
turtle.right(90)
turtle.forward(200)
turtle.down()
turtle.right(180)
# 花茎
turtle.pensize(8)
turtle.pencolor("green")
turtle.forward(100)
# 花叶
turtle.setheading(45)
turtle.circle(-120,60)
turtle.setheading(-135)
turtle.circle(-120,60)
turtle.setheading(135)
turtle.circle(120,60)
turtle.setheading(-45)
turtle.circle(120,60)
turtle.setheading(90)
turtle.forward(200)
# 花
turtle.pensize(1)
turtle.pencolor('orange')
turtle.fillcolor('yellow')
turtle.begin_fill()
# 画20个正方形
for i in range(20):
# 绘制正方形
for j in range(4):
turtle.forward(80)
turtle.left(90)
# 每次画完正方形调整画笔角度以免重复
turtle.left(18)
turtle.end_fill()
turtle.hideturtle()
input("Press Enter to exit...")
2)封装函数:
(2.1)动手试一试:
#封装函数(太阳花)
def flower():
太阳花代码
input("Press Enter to exit...")
(2.2 为什么运行不出来?)因为拥有“法卷轴”,但是没有使用它。
#不能运行,是因为只封装了函数,没有调用函数。
3)调用函数:函数名()
#封装函数(太阳花)
def flower():
太阳花代码
flower() #调用函数
input("Press Enter to exit...")
(3.1调用另一个函数)
#3.1调用一个函数运行
#移动画笔
turtle.up()
turtle.goto(-150,0)
turtle.down()
#调用函数
flower()
#3.2调用另一个函数运行
#移动画笔
turtle.up()
turtle.goto(150,0)
turtle.down()
#调用函数
flower(
4)做一个小练习吧!
四、含单个参数的函数
刚刚,画出来的太阳花颜色、大小都一样很呆板,能不能画出不同的太阳花?
1)括号():传递参数,向函数内传递信息。
2)参数列表:什么是参数?
例如:修改画笔颜色
import turtle
#画笔设置#理解什么是参数
turtle.pensize(8)
turtle.pencolor("green") #修改""里面的颜色
turtle.forward(200)
input("press enter to exit")
3)定义函数,接收参数
例如:画多边形
(3.1)画出多边形:
import turtle
#设置多边形的边数edge
edge=3 #可以修改edge调整多边形边数
for i in range(edge):
turtle.forward(80)
turtle.left(360/edge)
(3.2) 封装边数:把边封装到函数中,只用修改边数,就能改变多边形的形状。
#传入参数变量,没有值,只是一个形式,所以叫做形式参数,简称“形参
import turtle
#设置多边形的边数edge
def polygon(edge): #形参,传入参数变量,没有值,只是一个形式,所以叫做形式参数,简称“形参
for i in range(edge):
turtle.forward(80)
turtle.left(360/edge)
polygon(5) #实参,这个值运用到程序中,实际参数,简称"实参"
input("press enter to exit")
(3.3) 封装函数,就像列好了数学公式,输入值就可以出结果。
(3.4)参数:可以是0个,也可以1个,或多个。(可以是 常见数据类型/其他函数,作为参数)
四、太阳花代码(修改参数)
1)改 turtle.fillcolor(“yellow”) 为:
turtle.fillcolor(color)
2)改 def flower(): 为:
def flower(color):
3)改 flower() 为:
#3.1调用另一个函数运行
#移动画笔
turtle.up()
turtle.goto(-150,0)
turtle.down()
#调用函数
flower("yellow")
#3.2调用另一个函数运行
#移动画笔
turtle.up()
turtle.goto(150,0)
turtle.down()
#调用函数
flower("red")
input("Press Enter to exit...")