一、函数基础
-
函数是什么? 想象你每天都要重复做同一件事,比如泡咖啡。函数就像你写好的泡咖啡步骤说明书,每次需要时直接按步骤执行,不用重新想流程。
# 定义泡咖啡的函数 def make_coffee(sugar=1): # 默认加1勺糖 print("烧水...") print("放入咖啡粉...") print(f"加{sugar}勺糖") return "一杯咖啡做好了☕" # 调用函数 my_coffee = make_coffee(2) print(my_coffee)
-
函数的参数与返回值
-
参数类型
-
必须参数:调用时必须传递(如make_coffee(2)里的2)
-
默认参数:不传值时使用默认值(如sugar=1)
-
可变参数:接收任意数量参数(*args用于元组,**kwargs用于字典)
def student_info(name, age, *hobbies, **scores): print(f"姓名:{name}, 年龄:{age}") print("爱好:", hobbies) print("成绩:", scores) student_info("小明", 18, "篮球", "编程", 数学=90, 英语=85)
-
返回值
-
用return返回结果,可返回多个值(实际是元组)
-
无return时函数返回None
def calculator(a, b): add = a + b subtract = a - b return add, subtract result = calculator(10, 5) print(result) # 输出 (15, 5)
-
变量的作用域
-
局部变量:函数内部定义的变量(如函数内的add)
-
全局变量:函数外部定义的变量(需用global关键字修改)
count = 0 # 全局变量 def increment(): global count count += 1 print(f"当前计数:{count}") increment() # 输出 1
互动问题:如果去掉global count会报错吗?为什么?
二、常用数据结构
-
列表(List)
-
特点:可修改、有序、元素可重复
-
常用操作:增删改查
shopping_list = ["苹果", "牛奶"] shopping_list.append("面包") # 添加元素 shopping_list[1] = "酸奶" # 修改元素 shopping_list.pop() # 删除最后一个元素 print(shopping_list) # 输出 ['苹果', '酸奶']
-
字典(Dictionary)
-
特点:键值对结构,键不可重复
-
应用场景:存储用户信息、配置参数
user = { "name": "李华", "age": 25, "is_vip": True } print(user["name"]) # 输出 李华 user["email"] = "lihua@example.com" # 添加新键值对
-
元组(Tuple)与集合(Set)
-
元组:不可修改的列表,用圆括号定义
-
集合:自动去重,支持交集、并集操作
# 元组示例 colors = ("红色", "蓝色", "绿色") print(colors[0]) # 输出 红色 # 集合示例 fruit_set = {"苹果", "香蕉", "苹果", "橙子"} print(fruit_set) # 输出 {'苹果', '香蕉', '橙子'}
三、综合案例:学生成绩管理系统
students = [] def add_student(name, score): students.append({"name": name, "score": score}) def show_ranking(): sorted_students = sorted(students, key=lambda x: x["score"], reverse=True) for student in sorted_students: print(f"{student['name']}: {student['score']}分") # 添加学生 add_student("张三", 85) add_student("李四", 92) add_student("王五", 78) # 显示排名 show_ranking()
输出结果:
李四: 92分 张三: 85分 王五: 78分
思考题:如何修改代码实现按姓名排序?