1.函数
创建函数 def myFirstFunction():
print(" ")
调用函数 myFirstFunction()
函数设置参数 def add(a,b):
print(a+b)
调用: add(1+2)
函数的返回值: def add(a,b):
return a +b
2.函数文档:
def add(a,b):
"这是一个加法函数"
return a+b
访问文档: help(add)
add.__doc__ (分别两条下划线)
3. 关键字参数
def saysomething(name,words):
print(name + words)
调用:saysomething(name="小甲鱼",words="改变世界")
4.收集参数 没看懂,后续更
5.返回值 可以返回列表也可以返回元组
6.函数变量的作用域:
def discounts(price,rate):
final_price = price * rate
return final_price
old_price = float(input("请输入原价:"))
rate = float(input("请输入折扣率:"))
new_price = discounts(old_price,rate)
print("打折后的价格是:",new_price)
final_price 是局部变量,是在定义函数内部产生的
old_price, new_price是全局变量
区别:全局变量在整个代码中都可以访问得到,在函数内部不能去改变全局变量的值
7.global关键字 (全面的,整体的)
如果要在定义函数内部改变全局变量,可以在函数内部用 global更改
8.内嵌函数
def fun1():
print("fun1")
def fun2():
print("fun2")
fun2()
9.闭包 closure
在内部函数里对外部作用域(但不是在全局作用域)的变量进行引用,则这个内部函数就是一个闭包。
def funx(x):
def funy(y):
return x*y 定义funy(y)过程中用到了funx(x)的变量
return funy
所以funy就是一个闭包
在内部函数中,只能对外部函数的变量进行访问,但是不能进行修改
nonlocal (外地,非局部的,非本地的)
:在内部函数里修改外部函数里的局部变量的值
10. lambda 表达式 用lambda关键字来创建匿名函
def add(x,y):
return x + y
和 g = lambda x,y:x+y 效果一样
11.filter 过滤器
temp = filter(None,[1,0,False,True])
>>> list(temp)
[1, True]
filter(筛选准则,数组) ,根据筛选准则从数组里选择出True的元素输出
def odd(x):
return x % 2
list(filter(odd,range(10)))
或者如下:
list(filter(lambda x:x%2,range(10)))
用filter 删除1-100内的素数
def ss(x):
if x ==1 :
return True
for i in range(2,x):
if x % i == 0:
return True
return False
list(filter(ss,range(101)))
用filter 筛选出1-100内的素数
def ss(x):
if x==1:
return False
for i in range(2,x):
if x % 2 == 0:
return False
return True
list(filter(ss,range(101)))
12.map 映射迭代
map(运算法则,数组) 将数组里的每一个元素都按照运算法则进行运算
list(map(lambda x:x*x,range(10))) 将0—9每个数都平方 不是1—10哦
下次看第23个视频,课本第64页
总结今天所学:
global
closure
nonlocal
lambda
filter
map