今日目标
掌握 Python 三大控制流:条件分支、循环、函数和异常处理。
条件分支
python
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"elif 可以有零个或多个,else 可选。条件按顺序检查,匹配第一个就停止。
循环
while 循环
python
count = 0
while count < 5:
print(count)
count += 1当条件为 True 时反复执行。小心死循环——确保条件最终会变成 False。
for 循环
python
# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 使用 range
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 6): # 2, 3, 4, 5
print(i)
for遍历可迭代对象,while依赖条件。
break 和 continue
python
for n in range(10):
if n == 3:
continue # 跳过本次迭代
if n == 7:
break # 终止循环
print(n) # 输出: 0 1 2 4 5 6| 关键字 | 作用 |
|---|---|
break | 立即退出循环 |
continue | 跳过本次迭代,继续下一次 |
函数
python
def greet(name, greeting="Hello"):
"""返回问候语"""
return f"{greeting}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Hi")) # Hi, Bob!要点:
def定义函数,return返回值- 参数可以设默认值(
greeting="Hello") - 函数是一等对象——可以赋值给变量、作为参数传递
python
def apply(func, x):
return func(x)
def double(n):
return n * 2
print(apply(double, 5)) # 10异常处理
python
try:
num = int(input("输入一个数字: "))
result = 10 / num
print(f"结果: {result}")
except ValueError:
print("不是有效数字")
except ZeroDivisionError:
print("不能除以零")
except Exception as e:
print(f"未知错误: {e}")
else:
print("没有异常时执行")
finally:
print("无论如何都执行")| 块 | 何时执行 |
|---|---|
try | 正常代码 |
except | 捕获指定异常 |
else | 无异常时 |
finally | 必定执行(常用于资源清理) |
不要让异常悄悄吞掉。
except:(不指定类型)会捕获所有异常,包括你不想捕获的KeyboardInterrupt。始终指定异常类型。
今日要点:for 遍历集合、while 靠条件、函数是可复用的代码块、异常是程序的安全网。