全局變量? global_var
全局變量是定義在函數、類或者代碼塊外部的變量,它在整個程序文件內都能被訪問。在代碼里, global_var 就是一個全局變量,下面是相關代碼片段:
print("\n--- 變量作用域示例 ---")
global_var = "我是一個全局變量"
- 定義位置 : global_var 定義在函數 scope_test 外部,所以它是全局變量。
- 訪問權限 :全局變量可以在函數內部被訪問,如在 scope_test 函數里,通過 print(f"在函數內部,也可以看到全局變量: '{global_var}'") 就能訪問到 global_var 。
- 修改規則 :若要在函數內部修改全局變量,需要使用 global 關鍵字進行聲明。在代碼里,被注釋掉的 global_var = "嘗試在函數內修改全局變量" 這行代碼,如果沒有 global 聲明,Python 會創建一個新的局部變量 global_var ,而非修改全局變量。
局部變量? scope_var
局部變量是定義在函數、類或者代碼塊內部的變量,它只能在定義它的函數、類或者代碼塊內部被訪問。在代碼里, local_var 就是一個局部變量,相關代碼如下:
def scope_test():local_var = "我是一個局部變量"print(f"在函數內部,可以看到局部變量: '{local_var}'")
- 定義位置 : local_var 定義在 scope_test 函數內部,所以它是局部變量。
- 訪問權限 :局部變量只能在定義它的函數內部被訪問,在 scope_test 函數外部無法訪問 local_var 。如果嘗試在函數外部訪問 local_var ,Python 會拋出 NameError 異常。
- 生命周期 :局部變量的生命周期從函數開始執行時創建,到函數執行結束時銷毀。
總結
全局變量 :定義在函數外部,整個程序都能訪問,修改時需在函數內用 global 關鍵字聲明。
局部變量 :定義在函數內部,只能在函數內部訪問,函數執行結束后就會被銷毀。
參數
.title()
作用是把字符串中每個單詞的首字母轉換成大寫,其余字母轉換成小寫,最終返回一個新的字符串。
def describe_pet(animal_type, pet_name):"""顯示寵物的信息。"""print(f"\n我有一只 {animal_type}.")print(f"我的 {animal_type} 的名字叫 {pet_name.title()}.")describe_pet("貓", "咪咪") # 使用關鍵字參數,順序不重要
?*toppings
當函數參數前加上 * 時,這個參數就變成了可變參數。它能接收任意數量的位置參數,并將這些參數收集到一個元組中。在 make_pizza 函數里, *toppings 會把除了 size 之外的所有位置參數收集到一個元組里,這樣函數就能處理不同數量的配料了。
print(f"\n制作一個 {size} 寸的比薩,配料如下:")if toppings: # 只要toppings不為空元組,就會執行for topping in toppings:print(f"- {topping}")else:print("- 原味 (無額外配料)")
- print(f"\n制作一個 {size} 寸的比薩,配料如下:") :使用 f-string 格式化輸出,提示開始制作指定尺寸的披薩。
- if toppings: :檢查 toppings 元組是否為空。如果不為空,說明有額外配料。
- for topping in toppings: :遍歷 toppings 元組中的每個配料。
- print(f"- {topping}") :輸出每個配料的名稱。
- else: :如果 toppings 元組為空,說明沒有額外配料,輸出“原味 (無額外配料)”。
位置參數和關鍵詞參數區分?
從函數定義角度判斷
位置參數 :在函數定義時,沒有默認值且位于 *args 之前的參數通常是位置參數。在 process_data 函數里, id_num 和 name 就是位置參數,因為它們沒有默認值,并且在 *tags 之前。
def process_data(id_num, name, *tags, status="pending", **details):# ...
關鍵字參數 :有兩種情況。一種是像 status 這種有默認值的參數,它必須通過關鍵字形式傳值,被稱為僅關鍵字參數;另一種是 **details 這種可變關鍵字參數,它能接收任意數量的關鍵字參數。
?
從函數調用角度判斷
- 位置參數 :在函數調用時,按照函數定義中參數的順序依次傳入,不指定參數名的參數就是位置參數。例如:
?
process_data(103, "Charlie", "admin")
這里的 103 對應 id_num , "Charlie" 對應 name , "admin" 被 *tags 收集,它們都是按照位置傳遞的,所以是位置參數。
?關鍵字參數 :在函數調用時,通過 參數名=值 的形式傳入的參數就是關鍵字參數。例如:
process_data(name="David", id_num=104, profession="Engineer")
這里的 name="David" 、 id_num=104 和 profession="Engineer" 都是通過指定參數名來傳遞的,所以是關鍵字參數。
?總結
定義時:無默認值且在 *args 前的是位置參數;有默認值或在 * 之后的是關鍵字參數。
調用時:不指定參數名按順序傳的是位置參數;用 參數名=值 形式傳的是關鍵字參數。
作業
import mathdef calculate_circle_area(radius):try:if radius < 0:return 0else:return math.pi * radius ** 2except Exception:return 0# 計算半徑為5、0、-1時候的面積
print(calculate_circle_area(5))
print(calculate_circle_area(0))
print(calculate_circle_area(-1))
def calculate_rectangle_area(length, width):if length < 0 or width < 0:return 0else:return length * width
?
def calculate_average(*args):if not args:return 0total = sum(args)return total / len(args)
?
def print_user_info(user_id, **kwargs):print(f"用戶id: {user_id}")for key, value in kwargs.items():print(f"{key}: {value}")
def describe_shape(shape_name, color="black", **kwargs):dimensions_str = ""if kwargs:dim_parts = []for key, value in kwargs.items():dim_parts.append(f"{key}={value}")dimensions_str = ', '.join(dim_parts)else:dimensions_str = "no specific dimensions"return f"A {color} {shape_name} with dimensions: {dimensions_str}"desc1 = describe_shape("circle", radius=5, color="red")
print(desc1)
# 輸出: A red circle with dimensions: radius=5desc2 = describe_shape("rectangle", length=10, width=4)
print(desc2)
# 輸出: A black rectangle with dimensions: length=10, width=4desc3 = describe_shape("triangle", base=6, height=8, color="blue")
print(desc3)
# 輸出: A blue triangle with dimensions: base=6, height=8desc4 = describe_shape("point", color="green")
print(desc4)
# 輸出: A green point with no specific dimensions.
@浙大疏錦行