最专业的网站建设机构,腾讯企业邮箱登陆入口,搜索引擎营销的模式有,展示空间在线设计平台一、函数基础 函数是什么#xff1f; 想象你每天都要重复做同一件事#xff0c;比如泡咖啡。函数就像你写好的泡咖啡步骤说明书#xff0c;每次需要时直接按步骤执行#xff0c;不用重新想流程。 # 定义泡咖啡的函数 def make_coffee(sugar1): # 默认加1勺糖 print(…一、函数基础 函数是什么 想象你每天都要重复做同一件事比如泡咖啡。函数就像你写好的泡咖啡步骤说明书每次需要时直接按步骤执行不用重新想流程。 # 定义泡咖啡的函数 def make_coffee(sugar1): # 默认加1勺糖 print(烧水...) print(放入咖啡粉...) print(f加{sugar}勺糖) return 一杯咖啡做好了☕ # 调用函数 my_coffee make_coffee(2) print(my_coffee) 函数的参数与返回值 参数类型 必须参数调用时必须传递如make_coffee(2)里的2 默认参数不传值时使用默认值如sugar1 可变参数接收任意数量参数*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] lihuaexample.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, keylambda x: x[score], reverseTrue) 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分
思考题如何修改代码实现按姓名排序