1 #!/usr/bin/env python
2 #-*-coding:utf-8-*-
3 #_author_:Keep
4 '''
5 def area(width,height):
6 #calculate area
7 return width * height
8
9 def print_welcome(name):
10 print("Welcome!",name)
11 print_welcome("keep")
12 w = 5
13 h = 6
14 print("width =",w,"height =",h,"area = ",area(w,h))
15 '''
16
17 '''
18 #必需参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样。
19 def printme(str):
20 '打印任何传入的字符串'
21 print(str)
22 return
23 printme(str= "你好!")
24 '''
25 '''
26 def printinfo(name,age):
27 "打印任何传入的字符串"
28 print("名字:",name)
29 print("年龄:",age)
30 return
31 printinfo(age=88,name='keep')#函数参数的使用不需要使用指定顺序
32 printinfo('keep',50)
33 '''
34 '''
35 def printinfo(name,age = 23):
36 '打印任何传入的字符串'
37 print("名字:",name)
38 print("年龄:",age)
39 return
40 printinfo(name = 'keep',age = 25)
41 print("******************************")
42 printinfo(name = 'keep')
43 '''
44 '''
45 def printinfo(arg1,*vartuple):#加了星号 * 的参数会以元组(tuple)的形式导入,存放所有未命名的变量参数
46 print("输出:")
47 print(arg1)
48 print(vartuple)
49 #for var in vartuple:
50 # print(var)
51 return
52 printinfo(10,20,50)
53 '''
54 '''
55 def printinfo(arg1,**vardict):#加了两个星号 ** 的参数会以字典的形式导入
56 "打印传入任何形式的参数"
57 print("输出:")
58 print(arg1)
59 print(vardict)
60 printinfo(arg1 = 1,a = 2,b = 3)
61 '''
62 '''
63 #return [表达式] 语句用于退出函数,选择性地向调用方返回一个表达式。不带参数值的return语句返回None。
64 def sum(arg1,arg2):
65 '返回2个参数的值'
66 total = arg1 + arg2
67 print("函数内:",total)
68 return total
69 total = sum(10,30)
70 print("函数外:",total)
71 '''
72 '''
73 #在局部找不到,便会去局部外的局部找(例如闭包),再找不到就会去全局找,再者去内置中找。
74 total = 50 #全局变量
75 def sum(arg1,arg2):
76 "返回2个参数的积"
77 total = arg1 * arg2
78 print("函数内是局部变量:",total)
79 return total
80 sum(20,30)
81 print("函数外是全局变量:",total)
82 '''
83 '''
84 #修改全局变量需要用global
85 num = 2
86 def fun():
87 global num #需要使用global关键字声明
88 print(num)
89 num = 888
90 print(num)
91 fun()
92 print(num)
93 '''
94 '''
95 #修改作用域的变量需要用nonlocal
96 def outer():
97 num = 123
98 print(num)
99 def inner():
100 nonlocal num #nonlocal关键字声明
101 num = 789
102 print(num)
103 inner()
104 print(num)
105 outer()
106 '''
107 #递归函数:
108 def calc(n):
109 print(n)
110 if int(n/2) >0:
111 return calc(int(n/2))
112 print("***",n)
113 calc(10)