DAY 26 函数专题1:函数定义与参数
目录
- DAY 26 函数专题1:函数定义与参数
- 1.函数的定义
- 2.变量作用域:局部变量和全局变量
- 3.函数的参数类型:位置参数、默认参数、不定参数
- 4.传递参数的手段:关键词参数
- 5.传递参数的顺序:同时出现三种参数类型时
- 作业:
- 题目1:计算圆的面积
- 题目2:计算矩形的面积
- 题目3:计算任意数量数字的平均值
- 题目4:打印用户信息
- 题目5:格式化几何图形描述
DAY 26 函数专题1:函数定义与参数
1.函数的定义
def greet():message = '大家好!欢迎学习Python函数定义!'print(message)greet()
大家好!欢迎学习Python函数定义!
print(greet.__doc__)
None
def greet_person(name):message = f'你好, {name}! 很高兴认识你'print(message)greet_person('张三')
你好, 张三! 很高兴认识你
def add_features(feature1, feature2):total = feature1 + feature2print(f'{feature1} + {feature2} = {total}')add_features(10, 25)
10 + 25 = 35
def calculate_sum(a, b):result = a + breturn resultprint('hhh')calculate_sum(2, 3)
5
def preprocess_data(raw_data_points):processed = []for point in raw_data_points:processed.append(point * 2)return processeddata = [1, 2, 3, 4, 5]
processed_data = preprocess_data(data)print(f'原始数据: {data}')
print(f'预处理后数据: {processed_data}')
原始数据: [1, 2, 3, 4, 5]
预处理后数据: [2, 4, 6, 8, 10]
2.变量作用域:局部变量和全局变量
print('变量作用域示例')
global_var = '我是一个全局变量'def scope_test():local_var = '我是一个局部变量'print(f"在函数内部, 可以看到局部变量: '{local_var}'")print(f"在函数内部, 也可以看到全局变量: '{global_var}'")scope_test()print(f"在函数外部, 可以看到全局变量: '{global_var}'")
变量作用域示例
在函数内部, 可以看到局部变量: '我是一个局部变量'
在函数内部, 也可以看到全局变量: '我是一个全局变量'
在函数外部, 可以看到全局变量: '我是一个全局变量'
3.函数的参数类型:位置参数、默认参数、不定参数
def describe_pet(animal_type, pet_name):print(f'我有一只 {animal_type}')print(f'我的 {animal_type} 的名字叫 {pet_name.title()}')describe_pet('猫', '咪咪')
我有一只 猫
我的 猫 的名字叫 咪咪
describe_pet(animal_type='猫', pet_name='咪咪')
describe_pet(pet_name='旺财', animal_type='狗')
我有一只 猫
我的 猫 的名字叫 咪咪
我有一只 狗
我的 狗 的名字叫 旺财
def describe_pet_default(pet_name, animal_type='狗'):print(f'我有一只 {animal_type}')print(f'我的 {animal_type} 的名字叫 {pet_name.title()}')describe_pet_default(pet_name='小黑')
describe_pet_default(pet_name='雪球', animal_type='仓鼠')
我有一只 狗
我的 狗 的名字叫 小黑
我有一只 仓鼠
我的 仓鼠 的名字叫 雪球
def make_pizza(size, *toppings):print(f'制作一个 {size} 寸的比萨, 配料如下:')if toppings:for topping in toppings:print(f'{topping}')else:print('原味 (无额外配料)')make_pizza(12, '蘑菇')
make_pizza(16, '香肠', '青椒', '洋葱')
make_pizza(9)
制作一个 12 寸的比萨, 配料如下:
蘑菇
制作一个 16 寸的比萨, 配料如下:
香肠
青椒
洋葱
制作一个 9 寸的比萨, 配料如下:
原味 (无额外配料)
4.传递参数的手段:关键词参数
def build_profile(first_name, last_name, **user_info):profile = {}profile['first_name'] = first_nameprofile['last_name'] = last_namefor key, value in user_info.items():profile[key] = valuereturn profileuser_profile = build_profile('爱因斯坦', '阿尔伯特', location='普林斯顿', field='物理学', hobby='小提琴')
print(f'用户信息: {user_profile}')
用户信息: {'first_name': '爱因斯坦', 'last_name': '阿尔伯特', 'location': '普林斯顿', 'field': '物理学', 'hobby': '小提琴'}
5.传递参数的顺序:同时出现三种参数类型时
def process_data(id_num, name, *tags, status='pending', **details):print(f'ID: {id_num}')print(f'Name: {name}')print(f'Tags (*args): {tags}')print(f'Status: {status}')print(f'Details (**kwargs): {details}')print('-' * 20)process_data(101, 'Alice', 'vip', 'new_user', location='USA', age=30)
process_data(102, 'Bob', status='active', department='Sales')
process_data(103, 'Charlie', 'admin')
process_data(name='David', id_num=104, profession='Engineer')
ID: 101
Name: Alice
Tags (*args): ('vip', 'new_user')
Status: pending
Details (**kwargs): {'location': 'USA', 'age': 30}
--------------------
ID: 102
Name: Bob
Tags (*args): ()
Status: active
Details (**kwargs): {'department': 'Sales'}
--------------------
ID: 103
Name: Charlie
Tags (*args): ('admin',)
Status: pending
Details (**kwargs): {}
--------------------
ID: 104
Name: David
Tags (*args): ()
Status: pending
Details (**kwargs): {'profession': 'Engineer'}
--------------------
作业:
题目1:计算圆的面积
import mathdef calculate_circle_area(radius):if radius < 0:return 0else:return math.pi * (radius ** 2)print(f'Radius 5: {calculate_circle_area(5)}')
print(f'Radius 0: {calculate_circle_area(0)}')
print(f'Radius -1: {calculate_circle_area(-1)}')
Radius 5: 78.53981633974483
Radius 0: 0.0
Radius -1: 0
题目2:计算矩形的面积
def calculate_rectangle_area(length, width):if length < 0 or width < 0:return 0else:return length * widthprint(f'Length 5, Width 10: {calculate_rectangle_area(5, 10)}')
print(f'Length -5, Width 10: {calculate_rectangle_area(-5, 10)}')
print(f'Length 5, Width -10: {calculate_rectangle_area(5, -10)}')
Length 5, Width 10: 50
Length -5, Width 10: 0
Length 5, Width -10: 0
题目3:计算任意数量数字的平均值
def calculate_average(*args):if not args:return 0return sum(args) / len(args)print(f'Average of 1, 2, 3, 4, 5: {calculate_average(1, 2, 3, 4, 5)}')
print(f'Average of no numbers: {calculate_average()}')
Average of 1, 2, 3, 4, 5: 3.0
Average of no numbers: 0
题目4:打印用户信息
def print_user_info(user_id, **kwargs):print(f'User ID: {user_id}')for key, value in kwargs.items():print(f'{key}: {value}')print_user_info(114514, name='野兽先辈', city='下北泽')
User ID: 114514
name: 野兽先辈
city: 下北泽
题目5:格式化几何图形描述
def describe_shape(shape_name, color='black', **kwargs):description = f'A {color} {shape_name}'if not kwargs:description += ' with no specific dimensions.'else:dimensions = []for key, value in kwargs.items():dimensions.append(f'{key}={value}')description += ' with dimensions: ' + ', '.join(dimensions)return descriptionprint(describe_shape('circle', radius=5, color='red'))
print(describe_shape('rectangle', length=10, width=4))
print(describe_shape('triangle', base=6, height=8, color='blue'))
print(describe_shape('point', color='green'))
A red circle with dimensions: radius=5
A black rectangle with dimensions: length=10, width=4
A blue triangle with dimensions: base=6, height=8
A green point with no specific dimensions.
@浙大疏锦行