函数是一段代码的表示 def <函数名>(<参数(0个或多个)>):#()必须有 <函数体> <返回值> 参数(<非可选参数>,<可选参数>)#可选在后面 def fac(n,m=2): sum =1 for i in range(1,n+1): sum*=i return sum//m print(fac(5)) 60 print(fac(5,3)) 40 #1.位置传递,2.fac(m==3,n==5)名称传递 参数传递的2种方式 def fac(n,*m):# *m 为可变参数,数量不确定 sum =1 for i in range(1,n+1): sum*=i for j in m: sum*=j print(j,sum) return sum fac(5,3,2,6) 3 360 2 720 6 4320
函数可以没有返回值,return 用来传递返回值, 可以没有return . return 可以传递0个返回值,也可以传递任意多个返回值 >>> def fac(n,m=2): sum =1 for i in range(1,n+1): sum*=i return sum//m,n,m >>> fac(10,5) (725760, 10, 5) a,b,c = fac(10,5) print(a,b,c) 725760 10 5
n,s = 10,100 #n,s 为全局变量 def fac(n): s =1 #fac()函数里的n,s为局部变量 for i in range(1,n+1): s*=i return s print(fac(n),s) #n,s 为全局变量 3628800 100 函数运算结束后,局部变量被释放 可以使用global 保留字在函数内部使用全局变量 n,s = 10,100 def fac(n): global s #s 为全局变量 for i in range(1,n+1): s*=i return s print(fac(n),s) 362880000 362880000 局部变量为组合数据类型且未创建,等同于全局变量 ls = ['d','w'] def f(a): ls.append(a) return f('g') print(ls) ['d', 'w', 'g']
ls = ['s','e']
def f(a):
ls=[]
ls.append(a)
print(ls)
f('v')
print(ls)
['v']
['s', 'e']
7星管绘制时间
1 import turtle,time 2 def drawgap(): 3 turtle.pu() 4 turtle.fd(5) 5 def drawline(draw): 6 drawgap() 7 turtle.pd() if draw else turtle.pu() 8 turtle.fd(40) 9 drawgap() 10 turtle.rt(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.lt(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,5,7,8,9] else drawline(False) 20 turtle.lt(180) 21 turtle.pu() 22 turtle.fd(10) 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 turtle.pencolor('blue') 33 turtle.fd(40) 34 elif i =='+': 35 turtle.write('日',font=('Arial',18,'normal')) 36 else: 37 drawdigit(eval(i)) 38 def main(): 39 turtle.setup(800,350,200,200) 40 turtle.pu() 41 turtle.fd(-300) 42 turtle.pensize(5) 43 drawdate(time.strftime('%Y-%m=%d+',time.gmtime())) 44 turtle.hideturtle() 45 turtle.done() 46 main()
#判断素数 def prime(m): if m < 2: return False#首字母大写 else: end = int(pow(m, 0.5) + 1) for i in range(2, end): if m%i == 0: return False else: return True
#连续乘法 ''' def cmul(s): sum =1 for i in s: if i!=',': sum*=int(i) return sum s = input() sum = cmul(s) print(sum) ''' def cmul(a, *b): m = a for i in b: m *= i return m print(eval("cmul({})".format(input()))) 1,2,3,4,5 120
def dayup(df): daup = 1 for i in range(365): if i%7 in [0,6]: daup = daup*(1-0.01) else: daup = daup*(1+df) return daup#空格一定要合适 daf = 0.01 while dayup(daf) < 37.78: daf+=0.001 print("{:.3f}".format(daf))