# 小白學 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``