@浙大疏錦行
DAY 26 函數專題1
知識點回顧:
1.? 函數的定義
2.? 變量作用域:局部變量和全局變量
3.? 函數的參數類型:位置參數、默認參數、不定參數
4.? 傳遞參數的手段:關鍵詞參數
5.? 傳遞參數的順序:同時出現三種參數類型時
作業:
題目1:計算圓的面積
●?任務: 編寫一個名為 calculate_circle_area 的函數,該函數接收圓的半徑 radius 作為參數,并返回圓的面積。圓的面積 = π * radius2 (可以使用 math.pi 作為 π 的值)
●?要求:函數接收一個位置參數 radius。計算半徑為5、0、-1時候的面積
●?注意點:可以采取try-except 使函數變得更加穩健,如果傳入的半徑為負數,函數應該返回 0 (或者可以考慮引發一個ValueError,但為了簡單起見,先返回0)。
import math
def calculate_circle_area(radius):try:if radius < 0:return 0return 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))
題目2:計算矩形的面積
●?任務: 編寫一個名為 calculate_rectangle_area 的函數,該函數接收矩形的長度 length 和寬度 width 作為參數,并返回矩形的面積。
●?公式: 矩形面積 = length * width
●?要求:函數接收兩個位置參數 length 和 width。
○?函數返回計算得到的面積。
○?如果長度或寬度為負數,函數應該返回 0。
def calculate_rectangle_area(length, width):if length < 0 or width < 0:return 0return length * width
# 可以添加測試代碼來驗證函數功能
print(calculate_rectangle_area(5, 3))
print(calculate_rectangle_area(-1, 3))
print(calculate_rectangle_area(5, -2))
print(calculate_rectangle_area(0, 0))
題目3:計算任意數量數字的平均值
●?任務: 編寫一個名為 calculate_average 的函數,該函數可以接收任意數量的數字作為參數(引入可變位置參數 (*args)),并返回它們的平均值。
●?要求:使用 *args 來接收所有傳入的數字。
○?如果沒有任何數字傳入,函數應該返回 0。
○?函數返回計算得到的平均值。
def calculate_average(*args):if not args:return 0total = sum(args)return total / len(args)
# 測試函數
print(calculate_average(1, 2, 3, 4, 5))
print(calculate_average())
題目4:打印用戶信息
●?任務: 編寫一個名為 print_user_info 的函數,該函數接收一個必需的參數 user_id,以及任意數量的額外用戶信息(作為關鍵字參數)。
●?要求:
○?user_id 是一個必需的位置參數。
○?使用 **kwargs 來接收額外的用戶信息。
○?函數打印出用戶ID,然后逐行打印所有提供的額外信息(鍵和值)。
○?函數不需要返回值
def print_user_info(user_id, **kwargs):print(f"用戶ID: {user_id}")for key, value in kwargs.items():print(f"{key}: {value}")
# 測試函數
print_user_info(123, 姓名="張三", 年齡=25, 職業="工程師")
題目5:格式化幾何圖形描述
●?任務: 編寫一個名為 describe_shape 的函數,該函數接收圖形的名稱 shape_name (必需),一個可選的 color (默認 “black”),以及任意數量的描述該圖形尺寸的關鍵字參數 (例如 radius=5 對于圓,length=10, width=4 對于矩形)。
●?要求:shape_name 是必需的位置參數。
○?color 是一個可選參數,默認值為 “black”。
○?使用 **kwargs 收集描述尺寸的參數。
○?函數返回一個描述字符串,格式如下:
○?“A [color] [shape_name] with dimensions: [dim1_name]=[dim1_value], [dim2_name]=[dim2_value], …”如果 **kwargs 為空,則尺寸部分為 “with no specific dimensions.”
def describe_shape(shape_name, color="black", **kwargs):if kwargs:dimensions = ', '.join([f"{key}={value}" for key, value in kwargs.items()])return f"A {color} {shape_name} with dimensions: {dimensions}"else:return f"A {color} {shape_name} with no specific dimensions."
# 測試函數
desc1 = describe_shape("circle", radius=5, color="red")
print(desc1)
desc2 = describe_shape("rectangle", length=10, width=4)
print(desc2)
desc3 = describe_shape("triangle", base=6, height=8, color="blue")
print(desc3)
desc4 = describe_shape("point", color="green")
print(desc4)