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, height=1): # height为默认参数 """计算矩形面积""" # 文档字符串 return width * height # 调用函数 print(calculate_area(5, 4)) # 输出20 print(calculate_area(3)) # 使用默认height=1, 输出3 # 匿名函数 square = lambda x: x**2 print(square(4)) # 输出16注意事项:
- 参数传递:不可变对象传值,可变对象传引用
- 避免默认参数可变陷阱:
# 错误示范 def add_item(item, lst=[]): lst.append(item) return lst # 正确做法 def add_item(item, lst=None): 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("非法输入!")