Python零基础学习第三天:函数与数据结构

一、函数基础

  1. 函数是什么? 想象你每天都要重复做同一件事,比如泡咖啡。函数就像你写好的泡咖啡步骤说明书,每次需要时直接按步骤执行,不用重新想流程。
复制代码

定义泡咖啡的函数 def make_coffee(sugar=1): # 默认加1勺糖 print("烧水...") print("放入咖啡粉...") print(f"加{sugar}勺糖") return "一杯咖啡做好了☕" # 调用函数 my_coffee = make_coffee(2) print(my_coffee)

  1. 函数的参数与返回值
  • 参数类型

  • 必须参数:调用时必须传递(如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)

  1. 变量的作用域
  • 局部变量:函数内部定义的变量(如函数内的add)

  • 全局变量:函数外部定义的变量(需用global关键字修改)

复制代码
复制代码

count = 0 # 全局变量 def increment(): global count count += 1 print(f"当前计数:{count}") increment() # 输出 1

互动问题:如果去掉global count会报错吗?为什么?


二、常用数据结构

  1. 列表(List)
  • 特点:可修改、有序、元素可重复

  • 常用操作:增删改查

复制代码
复制代码

shopping_list = "苹果", "牛奶" shopping_list.append("面包") # 添加元素 shopping_list1 = "酸奶" # 修改元素 shopping_list.pop() # 删除最后一个元素 print(shopping_list) # 输出 '苹果', '酸奶'

  1. 字典(Dictionary)
  • 特点:键值对结构,键不可重复

  • 应用场景:存储用户信息、配置参数

复制代码
复制代码

user = { "name": "李华", "age": 25, "is_vip": True } print(user"name") # 输出 李华 user"email" = "lihua@example.com" # 添加新键值对

  1. 元组(Tuple)与集合(Set)
  • 元组:不可修改的列表,用圆括号定义

  • 集合:自动去重,支持交集、并集操作

复制代码
复制代码

元组示例 colors = ("红色", "蓝色", "绿色") print(colors0) # 输出 红色 # 集合示例 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分

思考题:如何修改代码实现按姓名排序?

相关推荐
金銀銅鐵5 小时前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li7 小时前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸11 小时前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学12 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田1 天前
Pydantic校验配置文件
python
hboot1 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi2 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽2 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187912 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python