Python编程——函数
函数的作用:
降低编程难度,将大问题分解为小问题。
实现代码重用,提高工作效率。
1、传值调用
Eg1:
[root@cate my_python]# python test_func
please input the value of s:hello world
the value of s is: hello world
[root@cate my_python]#
Eg2:
[root@cate my_python]# python test_func
please input the value of s1:hello
please input the value of s2:hello
hello = hello
[root@cate my_python]# python test_func
please input the value of s1:hello
please input the value of s2:world
hello != world
[root@cate my_python]#
2、 默认参数(缺省参数)
Eg1:指定左边的参数
[root@cate my_python]# python test_func
hello != default
[root@cate my_python]#
Eg2:全面使用缺省参数
[root@cate my_python]# python test_func
default = default
[root@cate my_python]#
Eg3:指定右边的参数
[root@cate my_python]# python test_func
default != yum
[root@cate my_python]#
eg4:形参的缺省参数自右向左开始
[root@cate my_python]# python test_func
hello != world
3、函数的实参可以是任意值,包括数字、字符串、列表[]、元组()、字典{}
[root@cate my_python]# python
Python 2.7.5 (default, Apr 11 2018, 07:36:10)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(x):
... print x
...
>>> f(10)
10
>>> f('hello')
hello
>>> f([1,2,3])
[1, 2, 3]
>>> f(range(6))
[0, 1, 2, 3, 4, 5]
>>> f(('a','b','c'))
('a', 'b', 'c')
>>> f({1:111,2:222,3:333})
{1: 111, 2: 222, 3: 333}
>>>
4、传递一个元组给2个形参
5、传递一个字典给两个形参
6、 传递多个参数
7、传递可变参数
8、lambda匿名函数
Eg1:lambda匿名函数的含义
Eg2:lambda匿名函数的使用
reduce函数每次取两个数实现阶乘