1 # 函数的定义及调用
2 # 函数只有被调用时才执行
3
4 # Demo 1
5 # 定义一个名为print_messages的函数打印hello world
6 # 无参数的函数
7
8 def print_messages():
9 print("hello world")
10
11
12 # 调用函数时输入函数名和括号即可
13 print_messages()
14
15
16 # Demo 2
17 # 向函数传递信息
18 # 函数定义时的参数为形参
19 # 函数调用时传入的参数为实参
20
21 def print_messages(name):
22 print("Hello, " + name.title() + "!")
23
24
25 # 调用函数时向函数传递一个名字
26 print_messages("tom")
27
28
29 # Demo 3
30 # 位置实参
31 # 调用函数时,Python必须将函数调用中的每个实参都关联到函数定义中的一个形参。为此,
32 # 最简单的关联方式是基于实参的顺序。这种关联方式被称为位置实参。
33
34
35 def print_messages(name, age):
36 print("My name is " + name.title() + " !")
37 print("My name is" + name.title() + "age " + str(age) + ".")
38
39
40 print_messages("tom", 10)
41
42
43 # Demo 4
44 # 默认参数
45 # 编写函数时,可给每个形参指定默认值。在调用函数中给形参提供了实参时,Python将使用
46 # 指定的实参值;否则,将使用形参的默认值。
47 # 默认参数调用时可传入也可以不传入值
48
49
50 def print_messages(name, age=10):
51 print("My name is " + name.title() + " !")
52 print("My name is " + name.title() + " age " + str(age) + ".")
53
54
55 print_messages("tom", 10)
56 print_messages("sam")
57
58
59 # Demo 5
60 # 函数的返回值
61 # 函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回
62 # 的值被称为返回值。
63
64 def print_name_messages(first_name, last_name):
65 full_name = first_name + " " + last_name
66 return full_name
67
68
69 name = print_name_messages("Li", "Duo")
70 print(name)
71
72
73 # Demo 6
74 # 参数类型为*args参数,只能通过位置传值如:
75 # 输出结果为元组形式
76
77 def print_messages(*args):
78 print("hello {}".format(args))
79
80
81 print_messages("jack", "tom")
82 print_messages("sam")
83
84
85 # Demo 7
86 # 参数为**kwargs参数,只能通过位置传值如:
87 # 输出结果为字典形式
88
89 def print_messages(**kwargs):
90 print(kwargs)
91
92
93 print_messages(a=1, b=2)
94
95
96 # Demo 8
97 # 函数的嵌套使用
98
99
100 def print_messages1():
101 print("Hello")
102 print_messages2()
103
104
105 def print_messages2():
106 print("World")
107
108
109 print_messages1()