Python 基础:控制流程
2.1 条件语句
python
age = 18
if age >= 18:
print("成年")
elif age >= 6:
print("青少年")
else:
print("儿童")
# 三元表达式
status = "成年" if age >= 18 else "未成年"1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
2.2 循环
for 循环
python
# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 遍历字典
person = {"name": "Alice", "age": 25}
for key in person:
print(f"{key}: {person[key]}")
# range 函数
for i in range(5): # 0,1,2,3,4
print(i)
for i in range(2, 8): # 2,3,4,5,6,7
print(i)
for i in range(0, 10, 2): # 0,2,4,6,8(步长2)
print(i)
# enumerate(带索引)
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
while 循环
python
count = 0
while count < 5:
print(count)
count += 1
# break 和 continue
for i in range(10):
if i == 3:
continue # 跳过 i=3
if i == 8:
break # 退出循环
print(i)1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
2.3 match 语句(Python 3.10+)
python
status = "success"
match status:
case "success":
print("操作成功")
case "error":
print("操作失败")
case _:
print("未知状态")1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
[[返回 Python 首页|python/index]]