《python基础教程》 --读书笔记(5)

函数,参数及作用域

创建函数

  • 使用def语句定义函数
# 定义函数
def fibs(num):
    result = [0, 1]
    for i in range(num-2):
        result.append(result[-2]+result[-1])
    return result
  • 文档化函数
    如果想要给函数写文档的,让其他使用者便于理解的话,可以加入注释(以#开头),另外一种方式就是写上字符串,在def语句后面及在模块或者类的开头
def sqare(num):
    "返回传入参数的平方"
    return num*num
#访问文档字符串
print(sqare.__doc__)
  • 函数返回值
    所有的函数都返回了东西,当没有返回值的时候,就返回None。
def test():
    print("会执行")
    return
    print("不会执行")
x = test() 
print(x)
#执行结果
会执行
None

参数

  • 形参实参
    写在def语句中函数名后面的变量通常叫做函数的形参,而调用函数的时候提供的值是实参,或者称为参数
  • 参数可以改变吗
    参数存储在局部作用域内,在函数内为参数赋予新值不会改变外部的任何变量
# 传入参数是否会被改变
# 1. 传入参数是否会被改变(字符串,数字,元组)
def to_change(n):
    return n*n

x = 3
a = to_change(x)
print("x = ", x,"a = ",a)

# 2. 传入参数是否会被改变(列表)
# 本例中,参数被改变了,这是因为两个变量同时引用一个列表的时候,他们的确是同时引用一个列表
def change(n):
    n[0] = "hello python"
lis = ["hello", "world"]
change(lis)
print(lis)

# 3. 传入参数是否会被改变(列表副本)
# 切片会返回副本
names = ["hello", "world"]
change(names[:])
print(names)
# 4. 需要修改参数的情况(初始化)
def init(data):
    data["first"] = {}
    data["middle"] = {}
    data["last"] = {}
storage = {}
init(storage)
print(storage)

#执行结果
x =  3 a =  9
['hello python', 'world']
['hello', 'world']
{'first': {}, 'middle': {}, 'last': {}}
  • 关键字参数和默认值
# 关键字参数 提供参数名字,便于记忆;提供默认值
def hello_1(greeting = "hello", name = "world"):
     print(greeting, name)
     
def hello_2(name="world", greeting="hello"):
    print(greeting, name)
    
hello_1()
hello_1("test")
hello_2(greeting = "test")

# 执行结果
hello world
test world
tast world
  • 收集参数
    函数接收任意多的参数
# 接受任意多的参数 返回元组
def print_params(*params):
    print(params)

print_params()
print_params("test")
print_params(1,2,3)

# 与普通参数联合使用
def print_params_2(title, *params):
    print(title)
    print_params(params)
print_params_2("Params: ", 1,2,3)

# 处理关键字参数 返回字典
def print_params_3(**params):
    print(params)
print_params_3(x = 1, y = 2, z = 3)

# 组合使用
def print_params_4(x, y, z=3, *pospar, **keypar):
    print(x, y, z)
    print("pospar =", pospar)
    print("keypar=", keypar)
print_params_4(1, 2, 3, 5, 6, 7, a=1, b=2)
print_params_4(1, 2)
()
('test',)
(1, 2, 3)
Params: 
((1, 2, 3),)
{'x': 1, 'y': 2, 'z': 3}
1 2 3
pospar = (5, 6, 7)
keypar= {'a': 1, 'b': 2}
1 2 3
pospar = ()
keypar= {}

作用域

出来全局作用域之外,每个函数调用都会创建一个新的作用域

# 作用域
def foo(): x =42
x = 1
foo()
print(x)
#执行结果
1
# 函数内部访问全局变量
a = 1
b = 10
def foo_1():
    b =5
    print(a)
    # 全局变量会被重名的局部变量屏蔽 使用globals函数
    print(b)
    print("globals_b =", globals()["b"])
foo_1()
#执行结果
1
5
globals_b = 10
# 重新绑定全局变量 使用global函数
def foo_2():
    global s
    s = 3
s = 1
foo_2()
print("s =",s)
#执行结果
s = 3
  • 嵌套作用域
# 闭包 函数存储子封闭作用域 函数本身被返回了,但并没有被调用
def multipplier(factor):
    def multipByFactor(number):
        return number*factor
    return multipByFactor

double = multipplier(2)
print(double(2)) # 4

triple = multipplier(3)
print(triple(2)) # 6

递归

  • 阶乘和幂
# 阶乘 递归方式实现
'''
1. 1的阶乘是1
2. 大于1的数n的阶乘是n乘n-1的阶乘
'''
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)
print(factorial(4))
# power(x, n)(x为n的幂次)
'''
1. 对于任意数字来说,power(x, 0)是1
2. 对于任何大于0的数来说,power(x, n)是x乘以power(x, n-1)的结果
'''
def power(x, n):
    if n == 0:
        return 1
    else:
        return x * power(x, n-1)
print(power(3,3))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章