万字干货,Python语法大合集,一篇文章带你入门( 七 )

函数使用def关键字来定义函数,我们在传参的时候如果指定函数内的参数名,可以不按照函数定义的顺序传参:
# Use "def" to create new functionsdef add(x, y):print("x is {} and y is {}".format(x, y))return x + y# Return values with a return statement# Calling functions with parametersadd(5, 6)# => prints out "x is 5 and y is 6" and returns 11# Another way to call functions is with keyword argumentsadd(y=6, x=5)# Keyword arguments can arrive in any order.复制代码可以在参数名之前加上*表示任意长度的参数,参数会被转化成list:
# You can define functions that take a variable number of# positional argumentsdef varargs(*args):return argsvarargs(1, 2, 3)# => (1, 2, 3)复制代码也可以指定任意长度的关键字参数,在参数前加上**表示接受一个dict:
# You can define functions that take a variable number of# keyword arguments, as welldef keyword_args(**kwargs):return kwargs# Let's call it to see what happenskeyword_args(big="foot", loch="ness")# => {"big": "foot", "loch": "ness"}当然我们也可以两个都用上,这样可以接受任何参数:
# You can do both at once, if you likedef all_the_args(*args, **kwargs):print(args)print(kwargs)"""all_the_args(1, 2, a=3, b=4) prints:(1, 2){"a": 3, "b": 4}"""传入参数的时候我们也可以使用*和**来解压list或者是dict:
# When calling functions, you can do the opposite of args/kwargs!# Use * to expand tuples and use ** to expand kwargs.args = (1, 2, 3, 4)kwargs = {"a": 3, "b": 4}all_the_args(*args)# equivalent to all_the_args(1, 2, 3, 4)all_the_args(**kwargs)# equivalent to all_the_args(a=3, b=4)all_the_args(*args, **kwargs)# equivalent to all_the_args(1, 2, 3, 4, a=3, b=4)Python中的参数可以返回多个值:
# Returning multiple values (with tuple assignments)def swap(x, y):return y, x# Return multiple values as a tuple without the parenthesis.# (Note: parenthesis have been excluded but can be included)x = 1y = 2x, y = swap(x, y)# => x = 2, y = 1# (x, y) = swap(x,y)# Again parenthesis have been excluded but can be included.复制代码函数内部定义的变量即使和全局变量重名,也不会覆盖全局变量的值 。想要在函数内部使用全局变量,需要加上global关键字,表示这是一个全局变量:
# Function Scopex = 5def set_x(num):# Local var x not the same as global variable xx = num# => 43print(x)# => 43def set_global_x(num):global xprint(x)# => 5x = num# global var x is now set to 6print(x)# => 6set_x(43)set_global_x(6)复制代码Python支持函数式编程,我们可以在一个函数内部返回一个函数:
# Python has first class functionsdef create_adder(x):def adder(y):return x + yreturn adderadd_10 = create_adder(10)add_10(3)# => 13复制代码Python中可以使用lambda表示匿名函数,使用:作为分隔,:前面表示匿名函数的参数,:后面的是函数的返回值:
# There are also anonymous functions(lambda x: x > 2)(3)# => True(lambda x, y: x ** 2 + y ** 2)(2, 1)# => 5复制代码我们还可以将函数作为参数使用map和filter,实现元素的批量处理和过滤 。关于Python中map、reduce和filter的使用,具体可以查看之前的文章:
五分钟带你了解map、reduce和filter
# There are built-in higher order functionslist(map(add_10, [1, 2, 3]))# => [11, 12, 13]list(map(max, [1, 2, 3], [4, 2, 1]))# => [4, 2, 3]list(filter(lambda x: x > 5, [3, 4, 5, 6, 7]))# => [6, 7]复制代码我们还可以结合循环和判断语来给list或者是dict进行初始化:
# We can use list comprehensions for nice maps and filters# List comprehension stores the output as a list which can itself be a nested list[add_10(i) for i in [1, 2, 3]]# => [11, 12, 13][x for x in [3, 4, 5, 6, 7] if x > 5]# => [6, 7]# You can construct set and dict comprehensions as well.{x for x in 'abcddeef' if x not in 'abc'}# => {'d', 'e', 'f'}{x: x**2 for x in range(5)}# => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}复制代码模块使用import语句引入一个Python模块,我们可以用.来访问模块中的函数或者是类 。
# You can import modulesimport mathprint(math.sqrt(16))# => 4.0复制代码我们也可以使用from import的语句,单独引入模块内的函数或者是类,而不再需要写出完整路径 。使用from import *可以引入模块内所有内容(不推荐这么干)
# You can get specific functions from a modulefrom math import ceil, floorprint(ceil(3.7))# => 4.0print(floor(3.7))# => 3.0# You can import all functions from a module.# Warning: this is not recommendedfrom math import *


推荐阅读