一、函数作用域
Python中作用域分为四种:
- 局部作用域 Local
- 嵌套作用域 Enclosing
- 全局作用域 Global
- 内置作用域 Built-in
示例:
x = str(100)
# str = 90 # built-in作用域
g_counter = 33 #全局作用域
def outer():
o_count = 0 #嵌套作用域
def inner():
i_counter = 5 #局部作用域
print(i_counter)
print(o_count)
print(g_counter)
inner()
outer()
- 作用域的产生:
if 2 > 1:
x = 3 # if没有引入新的作用域
print(x) # x可以被打出
def fun():
y = 3 # 函数引入了新的作用域
print(y) # 会报错
************************************************
x = 90
def f2():
print(x)
x = 88
print(x) # 90
f2()
print(x) # 178
- 局部作用域想要引用全局变量时使用global关键字:
count = 10
def outer():
global count
print(count)
count = 100
print(count)
outer()
#10
#100
- 局部作用域想要引用嵌套作用域的变量时使用nonlocal关键字:
def outer():
count = 10
def inner():
nonlocal count
count = 20
print(count)
inner()
print(count)
outer()
#20
#20
二、递归
在函数内部调用函数本身
- 举例:
def foo(n):
if n == 0:
return n
print(n)
foo(n-1)
print(foo(900))
- 阶乘:
用普通函数实现:
def jiecheng(n):
ret = n
for i in range(1,n):
ret *= i
return ret
用递归函数实现:
def jiecheng_new(n):
if n == 1:
return 1
return n * jiecheng_new(n - 1)
result = jiecheng_new(6)
print(result)
- 斐波那契数列:(1 1 2 3 5 8 13 21 34...)
普通函数实现:
def fibo(n):
before = 0
after = 1
for i in range(n-1):
ret = before + after
before = after
after = ret
print(before,end = '\t')
return ret
print(fibo(9))
递归函数实现:
def fibo_new(n):
if n <= 1:
return n
return fibo_new(n-1) + fibo_new(n-2)
print(fibo_new(9))
改进:
cache = {}
def fibo_new(n):
if n <= 1:
return n
if (n-1) not in cache:
cache[n-1] = fibo_new(n-1)
if (n-2) not in cache:
cache[n-2] = fibo_new(n-2)
return cache[n-1] + cache[n-2]
print(fibo_new(9))
- 水仙数
100~999中百位的立方加十位的立方加个位的立方等于这个数本身的数为水仙数
def shuixianhua():
temp = []
for i in range(100,1000):
a = i // 100
b = (i - a*100) // 10
c = i % 10
if a**3 + b**3 + c**3 == i:
temp.append(i)
return temp
print(shuixianhua())
三、导入模块与函数
要让函数是可导入的,得先创建模块。模块是扩展名为.py的文件,包含要导入到程序中的代码
- 格式:
1.import 模块名 #导入整个模块,调用函数时为 模块名.函数名
2.import 模块名 as 简称 #导入整个模块,调用函数时为 简称.函数名
3.from 模块名 import 函数名1,函数名2,... # 导入模块中特定的函数,调用
函数时可直接用函数名调用
4.from 模块名 import 函数名 as 简称 #导入模块中特定的函数,调用函数时可以直接用简称调用
5.from 模块名 import * #导入模块中所有的函数不推荐
四、函数的文档字符串
函数文档字符串是在函数开头,用来解释其接口的字符串。简而言之: 帮助文档。
- 包含函数的基础信息
- 包含函数的功能简介
- 包含每个形参的类型,使用等信息
- 必须在函数的首行,经过验证前面有注释性说明是可以的,不过最好函数文档出现在首行
- 使用三引号注解的多行字符串(当然,也可以是一行),因三引号可以实现多行注解(展示)(''' ''') 或(""" """)
- 函数文档的第一行一般概述函数的主要功能,第二行空,第三行详细描述。
查看方式:
def test(msg):
"""
函数名:test
功能:测试
参数:无
返回值:无
"""
print("函数输出成功"+msg)
test('hello')
print( help(test))
print(test.__doc__)