函数的使用
形参,实参
import time # 创建logger函数,等待传入的值为,形参 def logger(date): print("starting action1") with open("log.txt","a") as f: f.write("end save date: %s " %date) # 传入的值为,实参 logger(time.strftime("%Y-%m-%d %X"))
必须参数
必须要,对应,传入数量也必须一样
def print_info(name,age): print("name:%s" % name) print("age:%s" % age) print_info("Kidd",16)
关键词参数
根据形参的参数,来传实参
def print_info(name,age): print("name:%s"%name) print("age:%s"%age) print_info(age=16,name="Kidd")
默认参数
给形参传默认值,默认值形参,必须放到形参的最后
# 使用默认参数 def print_info(name,age=18): print("name:%s"%name) print("age:%s"%age) print_info("Kidd") # 不使用默认参数 def print_info(name,age=18): print("name:%s"%name) print("age:%s"%age) print_info(age=16,name="Kidd")
不定长参数
传入任意数量的实参 *
传入任意数量的关键词实参 **
def function(name="Bob",*args,**kwargs): print(name) print(*args) for key in kwargs: print("%s:%s"%(key,kwargs[key])) function("Kidd",1,2,3,age=16,sex="男") 运行结果: Kidd 1 2 3 age:16 sex:男
实参传入* , **
# 实参传 * 将列表,元祖中的元素提取出来 def func(*args): print(args) # (1, 2, 3, 4, 5, 6, [7,8,9]) func(*(1,2,3,),*[4,5,6],[789]) # 实参传 ** 将关键字传参,替换成了字典传参 def func1(**kwargs): print(kwargs) student1 = {"一斑":{"小明":{"age":15},"小红":{"age":14}}} student2 = {"二班":{"小李":{"age":15},"小张":{"age":16}}} func1(**student1,**student2) # {'一斑': {'小明': {'age': 15}, '小红': {'age': 14}}, '二班': {'小李': {'age': 15}, '小张': {'age': 16}}}
return
作用:函数的结束,函数的返回值
# return默认值None def function(*args): number = sum(args) print(number) # 6 number = function(1,2,3) print(number) # None # 使用return def function(*args): number = sum(args) return number number = function(1,2,3) print(number) # 6 # 返回多个数 def function(*args): number = sum(args) return number,7,[6,7],"6,7" number = function(1,2,3) # 返回一组元祖 print(number) # (6, 7, [6, 7], '6,7')
作用域
python的作用域,一共分为4种,分别是built,global,enclosing,local
x = int(2.0) # int built-in count = 0 # global def father(): father_name = "father" # enclosing def son(): son_name = "son" # local
高阶函数
1、函数名可以参数输入
2、函数名可以作为返回值
def first_portion(n): return n * n def second_portion(one,two,other): result = other(one) + other(two) return result print(second_portion(1,2,other=first_portion)) # 5
闭包
闭包 = 函数 + 定义函数时的环境
def outside(num): def inside(): print(num) return inside out = outside(10) out()
递归函数
#阶乘 #使用 for 循环 def multiply(n): number = 1 for i in range(1,n+1): number = i * number return number mul = multiply(5) print(mul) # 120 #使用递归 def multiply(n): if n == 1: return 1 return n * multiply(n-1) mul = multiply(5) print(mul) # 120 # 使用reduce 和 lambda from functools import reduce mul = reduce(lambda a,b : a*b,range(1,6)) print(mul)
使用递归,要有一个明确的结束条件,
递归的效率低,不如for循环
def addition(n): if n <= 2: return n return addition(n-1) + addition(n-2) add = addition(1) print(add)
斐波那契数列
def func(n): b,a,v = 0,1,0 for i in range(n): v = a + b b = a a = v print(a) func(5) def func1(n): b, a = 0, 1 for i in range(n): b,a = a,a+b print(a) func1(5)
两个结果一样,根据规律,使用最简单的
内置函数
filter(function,iterable)
# filter函数,相当于过滤器 iter_object = [1,2,3,4,5] def filter_function(num): if num > 1: return num object = filter(filter_function,iter_object) print(list(object)) # [2, 3, 4, 5]
map(func,iter1,iter2)
会根据提供的函数对指定序列做映射。
iter_name = ["小明:","小张:","小李:"] iter_sex = ["男","女","男"] def map_function(iter1,iter2): return iter1 + iter2 iter_content = map(map_function,iter_name,iter_sex) print(list(iter_content)) # ['小明:男', '小张:女', '小李:男']
reduce(function,sequence)
对参数序列中元素进行累积
from functools import reduce def add(x,y): return x + y num = reduce(add,range(1,101)) print(num) # 5050
lambda
lambda 匿名函数,它是一个表达式
用法: 参数 : 返回值
mul = reduce(lambda x,y:x*y,range(1,6)) print(mul) # 120 filter_lambda = filter(lambda a : a>1,range(1,6)) print(list(filter_lambda)) # [2, 3, 4, 5] map_lambda = map(lambda a : a ** 2,range(1,6)) print(list(map_lambda)) # [1, 4, 9, 16, 25]
chr
chr() 用一个范围在 range(256)内的(就是0~255)整数作参数,返回一个对应的字符。
其中 A-Z 对应的数值为 65-90
其中 a-z 对应的数值为 97 -122
for i in range(256): if chr(i) == "A": print(i) # 65 elif chr(i) == "a": print(i) # 97
ord
Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a')
returns the integer 97
and ord('€')
(Euro sign) returns 8364
. This is the inverse of chr()
.
ord('a') #97
enumerate
(iterable, start=0)
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__()
method of the iterator returned by enumerate()
returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.
for n,i in enumerate(range(1,10),1): print(n,i)
eval(expression, globals=None, locals=None)
The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.
x = 1 eval('x+1') #2
pow(x, y[, z])
Return x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than pow(x, y) % z
). The two-argument form pow(x, y)
is equivalent to using the power operator: x**y
.
pow(2,2) # 4 pow(2,2,3) # 1
More
https://docs.python.org/3/library/functions.html