1、函数
(1)定义:
(2)函数调用
(3)函数的参数传递
参数传递的两种方式:函数调用时,参数可以按照位置或名称的方式传递
(4)函数的返回值
(5)局部变量和全局变量
(6)lambda函数
2、实例:七段数码管的绘制
1 import turtle 2 def drawLine(draw): 3 turtle.pendown() if draw else turtle.penup() 4 turtle.fd(40) 5 turtle.right(90) 6 def drawDigit(digit): 7 drawLine(True) if digit in [2,3,4,5,6,8,9] else drawLine(False) 8 drawLine(True) if digit in [0,1,3,4,5,6,7,8,9] else drawLine(False) 9 drawLine(True) if digit in [0,2,3,5,6,8,9] else drawLine(False)10 drawLine(True) if digit in [0,2,6,8] else drawLine(False)11 turtle.left(90)12 drawLine(True) if digit in [0,4,5,6,8,9] else drawLine(False)13 drawLine(True) if digit in [0,2,3,5,6,7,8,9] else drawLine(False)14 drawLine(True) if digit in [0,1,2,3,4,7,8,9] else drawLine(False)15 turtle.left(180)16 turtle.penup()17 turtle.fd(20)18 def drawDate(date):19 for i in date :20 drawDigit(eval(i))21 def main():22 turtle.setup(800,350,200,200)23 turtle.penup()24 turtle.fd(-300)25 turtle.pensize(5)26 drawDate('20181010')27 turtle.hideturtle()28 turtle.done()29 main()
运行结果:
1 import turtle,time 2 def drawGap(): 3 turtle.penup() 4 turtle.fd(5) 5 def drawLine(draw): 6 drawGap() 7 turtle.pendown() if draw else turtle.penup() 8 turtle.fd(40) 9 drawGap()10 turtle.right(90)11 def drawDigit(digit):12 drawLine(True) if digit in [2,3,4,5,6,8,9] else drawLine(False)13 drawLine(True) if digit in [0,1,3,4,5,6,7,8,9] else drawLine(False)14 drawLine(True) if digit in [0,2,3,5,6,8,9] else drawLine(False)15 drawLine(True) if digit in [0,2,6,8] else drawLine(False)16 turtle.left(90)17 drawLine(True) if digit in [0,4,5,6,8,9] else drawLine(False)18 drawLine(True) if digit in [0,2,3,5,6,7,8,9] else drawLine(False)19 drawLine(True) if digit in [0,1,2,3,4,7,8,9] else drawLine(False)20 turtle.left(180)21 turtle.penup()22 turtle.fd(20)23 def drawDate(date):24 turtle.pencolor("red")25 for i in date :26 if i == '-':27 turtle.write("年",font=("Arial", 18, "normal"))28 turtle.pencolor("green")29 turtle.fd(40)30 elif i == '=':31 turtle.write("月",font=("Arial", 18, "normal"))32 elif i == '+':33 turtle.write("日",font=("Arial", 18, "normal"))34 else:35 drawDigit(eval(i))36 def main():37 turtle.setup(800,350,200,200)38 turtle.penup()39 turtle.fd(-300)40 turtle.pensize(5)41 drawDate(time.strftime("%Y-%m=%d+",time.gmtime()))42 #drawDate('20181010')43 turtle.hideturtle()44 turtle.done()45 main()
运行结果:(不知道问题出在哪里了)