Python学习日志(二):基础语法

张开发
2026/4/15 1:31:44 15 分钟阅读

分享文章

Python学习日志(二):基础语法
Python基础语法一、变量变量是存储数据的容器通过赋值语句创建name Alice # 字符串变量 age 25 # 整数变量 height 1.68 # 浮点数变量 is_student True # 布尔变量注意事项变量名区分大小写Age和age不同命名规范使用蛇形命名法如user_name动态类型变量类型由赋值自动确定避免使用Python关键字如print、for作变量名二、数据类型类型示例特性整型(int)42无大小限制浮点(float)3.14存在精度误差字符串(str)Python支持切片Py[0:2]布尔(bool)True/False逻辑运算基础列表(list)[1, a, True]可修改有序元组(tuple)(1, b)不可修改字典(dict){name: Bob}键值对映射集合(set){1, 2, 3}元素唯一无序类型转换函数int(10) → 10 str(3.14) → 3.14 list(abc) → [a,b,c]三、判断语句# 基础if-elif-else结构 score 85 if score 90: print(优秀) elif score 60: print(及格) # 输出此结果 else: print(不及格) # 三元表达式 status 通过 if score 60 else 未通过注意事项使用判断相等is判断对象标识空值判断if not list:优于if len(list)0:避免连续比较歧义1 x 10合法但x y z需谨慎四、循环结构1. while循环count 0 while count 5: print(f计数: {count}) count 1 # 必须更新循环变量!2. for循环# 遍历序列 fruits [apple, banana, cherry] for fruit in fruits: print(fruit) # 使用range for i in range(3): # 输出0,1,2 print(i) # 字典遍历 person {name: Tom, age: 20} for key, value in person.items(): print(f{key}: {value})循环控制break立即终止循环continue跳过当前迭代else循环正常结束时执行非break退出五、函数# 定义函数 def calculate_area(width, height1): # height为默认参数 计算矩形面积 # 文档字符串 return width * height # 调用函数 print(calculate_area(5, 4)) # 输出20 print(calculate_area(3)) # 使用默认height1, 输出3 # 匿名函数 square lambda x: x**2 print(square(4)) # 输出16注意事项参数传递不可变对象传值可变对象传引用避免默认参数可变陷阱# 错误示范 def add_item(item, lst[]): lst.append(item) return lst # 正确做法 def add_item(item, lstNone): lst lst or [] lst.append(item) return lst六、语法注意事项缩进规则使用4个空格非Tab作为缩进层级同一代码块必须严格对齐# 错误示例 if True: print(Hello) # IndentationError引号使用字符串可用单引号或双引号多行字符串用三引号或特殊运算符整除//如7//2→3幂运算**如2**3→8成员检测in如a in apple→True空值表示使用None非NULL或null七、综合实例学生成绩分析器def analyze_grades(grades): 分析成绩数据 if not grades: return 无有效数据 # 计算统计值 avg sum(grades) / len(grades) max_score max(grades) min_score min(grades) # 评级分布 levels {A: 0, B: 0, C: 0, D: 0} for score in grades: if score 90: levels[A] 1 elif score 80: levels[B] 1 elif score 70: levels[C] 1 else: levels[D] 1 # 返回结果字典 return { average: round(avg, 2), max: max_score, min: min_score, distribution: levels } # 测试数据 scores [92, 85, 76, 88, 69, 95, 62] result analyze_grades(scores) # 结果输出 print(f平均分: {result[average]}) print(f最高分: {result[max]}, 最低分: {result[min]}) print(等级分布:) for level, count in result[distribution].items(): print(f{level}级: {count}人)输出结果平均分: 81.0 最高分: 95, 最低分: 62 等级分布: A级: 2人 B级: 2人 C级: 2人 D级: 1人八、最佳实践总结变量使用描述性名称避免单字符除循环变量类型操作前验证数据类型如用type()或isinstance()循环优先选用for循环避免无限while函数遵循单一职责原则函数长度不超过50行异常处理使用try-except捕获潜在错误try: num int(input(输入数字: )) except ValueError: print(非法输入!)

更多文章