1.變數作用域
變數作用域決定了哪一部分的程式可以訪問哪乙個變數,python的變數作用域可以分為四種:
區域性作用域、閉包函式外的函式中、全域性作用域、內建作用域。程式會先在區域性作用域中尋找變數,沒找到的話,會去閉包函式外的函式中找,如果還是沒找到的話,會去全域性作用域找,如果還沒找到,會去內建作用域尋找。
各作用域如下面**所示
x = int(2.9) # 內建作用域
g_count = 0 # 全域性作用域
def outer():
o_count = 1 # 閉包函式外的函式中
def inner():
i_count = 2 # 區域性作用域
2.全域性變數與區域性變數
全域性變數:定義在函式外的變數,就是全域性變數
區域性變數:定義在函式內的變數,就是區域性變數
total = 0 # 這是乙個全域性變數
# 可寫函式說明
def sum(arg1, arg2):
# 返回2個引數的和."
total = arg1 + arg2 # total在這裡是區域性變數.
print("函式內是區域性變數 : ", total)
return total
# 呼叫sum函式
sum(10, 20)
print("函式外是全域性變數 : ", total)
3.global與nonlocal關鍵字
global用於區域性作用域修改全域性作用域變數,如下**
num = 1
def fun1():
global num # 需要使用 global 關鍵字宣告
print(num)
num = 123
print(num)
fun1()
print(num)
nonlocal用於區域性作用域修改外層非全域性作用域變數,如下**
def outer():
num = 10
def inner():
nonlocal num # nonlocal關鍵字宣告
num = 100
print(num)
inner()
print(num)
outer()
Python基礎函式學習筆記 二
一 格式化列印輸出 乙個輸出時 兩個輸出時 輸出換行 print預設輸出自動加換行,如下所示 rabbits 20 print rabbits cages 15 print cages 結果如下所示 如果要在同一行顯示的話,可以在行末加逗號,如下 二 使用者輸入 兩個函式input和raw inpu...
python 函式學習
今兒再網上看了下別人總結的python 函式,功能挺強大的,c有的功能都有,下面就記些它的功能點 1 定義,格式跟c不一樣,概念是一樣的。def 函式名 引數列表 函式語句 return 返回值 2 函式可以命別名,很方便啊,c語言我記憶中只有指標可以。def sum list result 0 f...
Python函式學習
def hello name return hello,name print hello holly defhello name print hello,name hello holly 輸出結果為hello,holly!稍微複雜一點的例子有 求長方體的體積 def volume length,wi...