python函数篇(四)

函数

函数是一段可以重复使用的代码块,用来执行特定的任务。函数通过def关键字定义,可以接受输入参数(也称为参数或实参),并且可以返回一个或多个值

Python函数的名称通常由小写字母组成,如果名称包含多个单词,建议使用下划线_来分隔单词。这种命名方式称为“蛇形命名法”或“snake_case

避免使用Python保留字

  • Python有一些保留字(关键字),例如if、while、for、return等,这些是Python语言的语法组成部分,不能用作函数名

函数的定义与调用

定义一个函数的基本语法如下:

def 函数名(参数1, 参数2, ...):
    函数体
    return 返回值

例如,下面是一个简单的函数,它接受两个参数并返回它们的和

def add(a, b):
    return a + b

参数和参数传递

  • 函数可以接受零个、一个或多个参数。参数是传递给函数的信息,可以在函数内部使用。函数的参数传递方式有两种:

    • 按位置传递:参数按照定义时的位置顺序传递。
    • 按名称传递(关键字参数):参数可以通过名称指定,这样可以不考虑顺序。
def introduce(name, age):
    print(f"My name is {name} and I am {age} years old.")

# 按位置传递
introduce("Alice", 30)

# 按名称传递
introduce(age=25, name="Bob")

参数与返回值

默认参数

  • 在定义函数时,可以为某些参数设置默认值。如果调用函数时没有提供这些参数的值,则使用默认值。
def greet(name, message="Hello"):
    print(f"{message}, {name}!")

greet("Alice")
greet("Bob", "Good morning")

在这个例子中,如果调用greet函数时没有提供message参数,默认会使用“Hello”

可变数量的参数

  • Python允许函数接受可变数量的参数,使用*args和**kwargs来处理:

    • *args:用于接收不定数量的普通参数,参数会被打包成一个元组。
    • **kwargs:用于接收不定数量的关键字参数,参数会被打包成一个字典
def my_function(*args, **kwargs):
    print("Positional arguments:", args)
    print("Keyword arguments:", kwargs)

my_function(1, 2, 3, a=4, b=5)

函数可以使用return语句返回一个值,如果没有return语句或者return没有指定值,则函数默认返回None。函数也可以返回多个值,这些值会作为元组返回

def add_subtract(a, b):
    return a + b, a - b

result = add_subtract(10, 5)
print(result)  # 输出 (15, 5)

默认参数与关键字参数

使用默认参数的规则:

  • 默认参数必须位于非默认参数之后。这意味着在函数定义中,必须先定义没有默认值的参数,然后才能定义有默认值的参数。
def greet(name, message="Hello"):
    print(f"{message}, {name}!")

# 调用时只提供必需参数
greet("Alice")  # 输出: Hello, Alice!

# 调用时提供了所有参数
greet("Bob", "Good morning")  # 输出: Good morning, Bob!

使用关键字参数的规则:

  • 关键字参数可以以任何顺序出现,并且不必担心参数顺序问题。
    关键字参数在传递时必须使用参数名称。
def introduce(name, age, city="Unknown"):
    print(f"My name is {name}, I am {age} years old, and I live in {city}.")

# 使用关键字参数调用
introduce(name="Alice", age=30, city="New York")
# 输出: My name is Alice, I am 30 years old, and I live in New York.

# 也可以混合位置参数和关键字参数
introduce("Bob", age=25)
# 输出: My name is Bob, I am 25 years old, and I live in Unknown.

默认参数和关键字参数常常结合使用,提供了很大的灵活性。可以在函数定义中为某些参数提供默认值,并在调用时根据需要通过关键字参数来覆盖这些默认值

def make_greeting(name, greeting="Hello", punctuation="!"):
    return f"{greeting}, {name}{punctuation}"

# 使用所有默认参数
print(make_greeting("Alice"))  # 输出: Hello, Alice!

# 覆盖默认的greeting参数
print(make_greeting("Bob", greeting="Hi"))  # 输出: Hi, Bob!

# 覆盖所有默认参数
print(make_greeting("Charlie", greeting="Good morning", punctuation="."))  
# 输出: Good morning, Charlie.

匿名函数(lambda表达式)

Python还支持匿名函数,通常用lambda关键字定义,可以让在需要时快速定义一个简单的函数,而无需使用def语句。它们通常用于那些逻辑简单、不需要多次重复使用的场合

add = lambda x, y: x + y
print(add(3, 5))  # 输出 8

作用域:局部变量与全局变量

在函数内部定义的变量是局部变量,只能在函数内部访问。而在函数外部定义的变量是全局变量,可以在函数内外访问;函数内部的x是局部变量,不会影响全局变量x的值

x = 10  # 全局变量

def func():
    x = 5  # 局部变量
    print("Inside function:", x)

func()
print("Outside function:", x)

函数的嵌套与闭包

函数可以嵌套定义,即在一个函数内部定义另一个函数。嵌套函数可以访问其外层函数的变量。这种技术通常用于创建闭包

def outer_function(msg):
    def inner_function():
        print(msg)
    return inner_function

closure = outer_function("Hello")
closure()  # 输出 "Hello"

inner_function是一个闭包,因为它“记住”了外部函数outer_function的msg变量

案例实操

开发一个简单的学生成绩管理系统。这个系统可以执行以下任务:

  • 添加学生及其成绩。
    计算每个学生的平均成绩。
    找到班级中的最高分和最低分。
    显示班级的整体平均成绩

定义主要函数;

添加学生及其成绩,成绩存储在一个字典中,其中键是学生的名字,值是一个由成绩组成的列表

def add_student(student_records, name, scores):
    student_records[name] = scores

计算每个学生的平均成绩

def calculate_average(scores):
    return sum(scores) / len(scores)

找到班级中的最高分和最低分

def find_highest_and_lowest(student_records):
    highest_score = float('-inf')
    lowest_score = float('inf')
    for scores in student_records.values():
        if max(scores) > highest_score:
            highest_score = max(scores)
        if min(scores) < lowest_score:
            lowest_score = min(scores)
    return highest_score, lowest_score

显示班级的整体平均成绩

def calculate_class_average(student_records):
    total_scores = 0
    total_count = 0
    for scores in student_records.values():
        total_scores += sum(scores)
        total_count += len(scores)
    return total_scores / total_count

功能实现

def main():
    student_records = {}

    # 添加学生及其成绩
    add_student(student_records, "Alice", [85, 92, 78])
    add_student(student_records, "Bob", [88, 90, 94])
    add_student(student_records, "Charlie", [95, 85, 80])

    # 计算并显示每个学生的平均成绩
    for name, scores in student_records.items():
        average = calculate_average(scores)
        print(f"{name}'s average score is: {average:.2f}")

    # 找到并显示最高分和最低分
    highest, lowest = find_highest_and_lowest(student_records)
    print(f"The highest score in the class is: {highest}")
    print(f"The lowest score in the class is: {lowest}")

    # 计算并显示班级的平均成绩
    class_average = calculate_class_average(student_records)
    print(f"The class average score is: {class_average:.2f}")

# 运行主函数
if __name__ == "__main__":
    main()
# 定义添加学生及其成绩的函数
def add_student(student_records, name, scores):
    student_records[name] = scores

# 定义计算某个学生平均成绩的函数
def calculate_average(scores):
    return sum(scores) / len(scores)

# 定义找到班级最高分和最低分的函数
def find_highest_and_lowest(student_records):
    highest_score = float('-inf')
    lowest_score = float('inf')
    for scores in student_records.values():
        if max(scores) > highest_score:
            highest_score = max(scores)
        if min(scores) < lowest_score:
            lowest_score = min(scores)
    return highest_score, lowest_score

# 定义计算班级平均成绩的函数
def calculate_class_average(student_records):
    total_scores = 0
    total_count = 0
    for scores in student_records.values():
        total_scores += sum(scores)
        total_count += len(scores)
    return total_scores / total_count

# 主函数,用于组织程序的执行流程
def main():
    student_records = {}

    # 添加学生及其成绩
    add_student(student_records, "Alice", [85, 92, 78])
    add_student(student_records, "Bob", [88, 90, 94])
    add_student(student_records, "Charlie", [95, 85, 80])

    # 计算并显示每个学生的平均成绩
    for name, scores in student_records.items():
        average = calculate_average(scores)
        print(f"{name}'s average score is: {average:.2f}")

    # 找到并显示最高分和最低分
    highest, lowest = find_highest_and_lowest(student_records)
    print(f"The highest score in the class is: {highest}")
    print(f"The lowest score in the class is: {lowest}")

    # 计算并显示班级的平均成绩
    class_average = calculate_class_average(student_records)
    print(f"The class average score is: {class_average:.2f}")

# 判断是否以脚本形式运行,如果是则执行主函数
if __name__ == "__main__":
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

huhy~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值