函数《潭州学院(心蓝)》

 1 def print_twice(arg):
 2     """
 3     打印两次
 4     :param arg:
 5     :return:
 6     """
 7     print(arg)
 8     print(arg)
 9     return arg
10 
11 res = print_twice('hello word')
12 print(res)
13 
14 
15 # 需求:写一个函数,接受两个数,返回这两数的和
16 def my_sum(x, y):  # 普通参数
17     print('x=', x, 'y=', y)
18     res = x + y
19     return res
20 
21 add = my_sum(1, 2)  # 位置参数,传入的实参按照顺序形式一一对应
22 add1 = my_sum(x=1, y=2)  # 关键字参数,以形参名=实参名的方式传输
23 add2 = my_sum(y=2, x=1)  # 不按照顺序的
24 print(add)
25 
26 
27 # 需求:写一个函数,接收两个数和一个四则运算符号,返货这两个数运算结果
28 def my_func(x, y, method='+'):  # 为默认参数,默认参数放在普通参数后面
29     print('x=', x, 'y=', y, 'method=', method)
30     if method == '+':
31         ress = x + y
32     elif method == '-':
33         ress = x - y
34     elif method == '*':
35         ress = x * y
36     elif method == '/':
37         ress = x / y
38     else:
39         ress = '符号错误'
40     return ress
41 
42 add_data = my_func(1, 2, '-')
43 print(add_data)
44 
45 
46 # 需求:写一个函数返回接受的所有数的和
47 def my_func2(x, *args):  # 位置动态参数,将函数接收到的多余的位置参数当作一个元组给args
48     print(args)
49 
50 my_func2(1, 2, 3, 4)
51 
52 
53 def my_func3(**kwargs):  # 关键字动态参数,将函数接收到的多余的关键字参数当作一个字典给akwargs
54     print(kwargs)
55 
56 my_func3(x=1, y=2, z=3)
57 # {'x': 1, 'y': 2, 'z': 3}
58 
59 
60 def my_func4(y, **kwargs):  # 关键字动态参数,将函数接收到的多余的关键字参数当作一个字典给akwargs
61     print(kwargs)
62 
63 my_func4(x=1, y=2, z=3)
64 # {'x': 1, 'z': 3}
65 
66 
67 def my_func5(x, y, method='+'):  # 为默认参数,默认参数放在普通参数后面
68     print('x=', x, 'y=', y, 'method=', method)
69     if method == '+':
70         ress = x + y
71     elif method == '-':
72         ress = x - y
73     elif method == '*':
74         ress = x * y
75     elif method == '/':
76         ress = x / y
77     else:
78         ress = '符号错误'
79     return ress
80 
81 add_data = [1, 2, '-']  # 列表
82 print(type(add_data))
83 res = my_func5(*add_data)  # 将序列的元素按照位置参数的方式传入函数
84 # => res = my_func(1, 2, '-')
85 print(res)
86 
87 add_data1 = {'x': 1, 'y': 2, 'method': '-'}  # 字典
88 res1 = my_func5(add_data1['x'], add_data1['y'], add_data1['method'])
89 # =>res =  my_func(x = 1, y = 2, method = '-') 字典键值对{键:值}
90 print(res1)
91 
92 res2 = my_func5(**add_data1)  # 将字典中的元素按照关键字参数形式传入参数
93 # =>res =  my_func(x = 1, y = 2, method = '-')
94 print(res2)

 

posted on 2018-02-11 23:06  新手爱好者  阅读(217)  评论(0编辑  收藏  举报

导航