# PYG601.py 函数
def func(x):
if x > 0:
return x
print (filter(func, range(-9, 10))) # 调用filter函数,返回的是filter对象
print(list(filter(func, range(-9, 10)))) # 将filter对象转换为列表
# pyg60101.py
def sum(x, y):
return x + y
from functools import reduce # 引入reduce
print (reduce(sum, range(0, 10))) #0+1+2+3+4+5+6+7+8+9
print (reduce(sum, range(0, 10), 10)) #0+1+2+3+4+5+6+7+8+9+10
print (reduce(sum, range(0, 0), 10)) #0+10
# pyg60102.py
def power(x): return x ** x
print (map(power, range(1, 5))) # 打印map对象
print(list(map(power,range(1,5)))) # 转换为列表输出
def power2(x, y): return x ** y
print (map(power2, range(1, 5), range(5, 1, -1))) # 打印map对象
print(list(map(power2, range(1, 5), range(5, 1, -1)))) # 转换为列表输出
# 函数的默认参数
def arithmetic(x=1, y=1, operator="+"):
result = {
"+" : x + y,
"-" : x - y,
"*" : x * y,
"/" : x / y
}
return result.get(operator) # 返回计算结果
print (arithmetic(1, 2))
print (arithmetic(1, 2, "-"))
print (arithmetic(y=3, operator="-"))
print (arithmetic(x=4, operator="-"))
print (arithmetic(y=3, x=4, operator="-"))
# 传递可变参数
def search(*t, **d):
keys = d.keys()
values = d.values()
print(keys)
print (values)
for arg in t:
for key in keys:
if arg == key:
print ("find:",d[key])
search("one", "three", one="1",two="2",three="3")
# 嵌套函数
def sum(a, b):
return a + b
def sub(a, b):
return a - b
def func():
x = 1
y = 2
m= 3
n = 4
return sum(x, y) * sub(m, n)
print (func())
# 嵌套函数
def func():
x = 1
y = 2
m= 3
n = 4
def sum(a, b): # 内部函数
return a + b
def sub(a, b): # 内部函数
return a - b
return sum(x, y) * sub(m, n)
print (func())
# 计算阶乘
def refunc(n):
i = 1
if n > 1: # 递归的结束判断
i = n
n = n * refunc(n-1) # 递推
print ("%d! =" %i, n)
return n # 回归
refunc(10)
# 自定义模块
def func():
print ("MyModule.func()")
class MyClass:
def myFunc(self):
print ("MyModule.MyClass.myFunc()")
MyClass.myFunc(func())