python学习day26

函数专题1:函数定义与参数
知识点回顾:
1.函数的定义
2.变量作用域:局部变量和全局变量
3.函数的参数类型:位置参数、默认参数、不定参数
4.传递参数的手段:关键词参数
5.传递参数的顺序:同时出现三种参数类型时
*args 元组 **kwargs字典

#函数
def function_name(parameter1, parameter2, ...):
    """
    Docstring: 描述函数的功能、参数和返回值 (可选但强烈推荐)
    """
    # 函数体: 实现功能的代码
    # ...
    return value # 可选,用于返回结果


题目1:计算圆的面积
●任务: 编写一个名为 calculate_circle_area 的函数,该函数接收圆的半径 radius 作为参数,并返回圆的面积。圆的面积 = π * radius² (可以使用 math.pi 作为 π 的值)
●要求:函数接收一个位置参数 radius。计算半径为5、0、-1时候的面积
●注意点:可以采取try-except 使函数变得更加稳健,如果传入的半径为负数,函数应该返回 0 (或者可以考虑引发一个ValueError,但为了简单起见,先返回0)。
 

import math

def calculate_circle_area(radius):
    try:
        if radius < 0: 
            raise ValueError("Radius cannot be negative")
        return math.pi * (radius ** 2)
    except ValueError:
        return 0

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):
    try:
        if length < 0 or width < 0:
            raise ValueError("Length and width must be non-negative.")
    
        return length * width
    except ValueError as e:
        print(f"Error: {e}")
        return 0
    return area
a = int(input())
b = int(input())
print(calculate_rectangle_area(a, b))

题目3:计算任意数量数字的平均值
●任务: 编写一个名为 calculate_average 的函数,该函数可以接收任意数量的数字作为参数(引入可变位置参数 (*args)),并返回它们的平均值。
●要求:使用 *args 来接收所有传入的数字。
○如果没有任何数字传入,函数应该返回 0。
○函数返回计算得到的平均值。

def calculate_average( *args):
    if not args:
        return 0
    else:
        return sum(args)/len(args)

print(calculate_average(1,2,3,4,5))
print(calculate_average(1,2,3,4,5,6,7,8,9,10))
print(calculate_average())

题目4:打印用户信息
●任务: 编写一个名为 print_user_info 的函数,该函数接收一个必需的参数 user_id,以及任意数量的额外用户信息(作为关键字参数)。
●要求:
○user_id 是一个必需的位置参数。
○使用 **kwargs 来接收额外的用户信息。
○函数打印出用户ID,然后逐行打印所有提供的额外信息(键和值)。
○函数不需要返回值

def print_user_info(user_id, **kwargs):
    message = {}
    message['user_id'] = user_id
    for key, value in kwargs.items():
        message[key] = value
    return message

exp1 = print_user_info(1, name='Bob', age=20)
print(exp1)
exp2 = print_user_info(2, name='Alice', age=30, country='China')
print(exp2)

题目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):
    descirbe_text = ', '.join(f"{key}={value}" for key,value in kwargs.items())
    if not kwargs:
        descirbe_text = 'with no specific dimensions'
    return f"A {color} {shape_name} with dimensions: {descirbe_text}"

desc1 = describe_shape("circle", radius=5, color="red")
print(desc1)
# 输出: A red circle with dimensions: radius=5

desc2 = describe_shape("rectangle", length=10, width=4)
print(desc2)
# 输出: A black rectangle with dimensions: length=10, width=4

desc3 = describe_shape("triangle", base=6, height=8, color="blue")
print(desc3)
# 输出: A blue triangle with dimensions: base=6, height=8

desc4 = describe_shape("point", color="green")
print(desc4)
# 输出: A green point with no specific dimensions.

@浙大疏锦行

你可能感兴趣的:(python学习笔记,python,学习,开发语言)