# 小白学 Python（17）：基础数据类型（函数）（下）

## 变量作用域

``````a = 0

def print_1():
a = 1
print('a =', a)

def print_2():
a = 2
print('a =', a)

print_a()``````

``a = 1``

``````a = 0

def print_1():
a = 1
print('a =', a)

def print_2():
a = 2
print('a =', a)

print('a =', a)``````

``a = 0``

``````a = 0

def print_1():
# a = 1
print('a =', a)

def print_2():
a = 2
print('a =', a)

print_a()``````

``a = 0``

``````a = 0

def print_1():
# a = 1
print('a1 =', a)

def print_2():
a = 2
print('a2 =', a)

print_2()

print('a3 =', a)
print_1()``````

``````a3 = 0
a1 = 0
a2 = 2``````

## 匿名函数

• lambda 只是一个表达式，函数体比 def 简单很多。
• lambda的主体是一个表达式，而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。
• lambda 函数拥有自己的命名空间，且不能访问自己参数列表之外或全局命名空间里的参数。

``函数对象名 = lambda 形参：表达式``

``````add = lambda x,y: x + y

``3``

``````max_num = lambda x,y: x if x >= y else y

print(max_num(5, 9))``````

``9``

## 递归函数

`n! = 1 * 2 * 3 * ... * n`

``````def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)

print('10的阶乘为：', factorial(10))``````

``10的阶乘为： 3628800``