文章目录
- 一、条件控制结构
-
-
- [`if` 语句](#
if
语句) - [`else` 语句](#
else
语句) - [`elif` 语句](#
elif
语句) - 嵌套条件语句
- match...case
- 条件表达式(三元运算符)
- [`if` 语句](#
-
- 二、循环语句
-
-
- [while 循环](#while 循环)
- 无限循环
- while.......else语句
- [for 循环](#for 循环)
- for...else语句
-
- 三、循环控制
-
-
- break语句
- continue语句
- [pass 语句](#pass 语句)
-
-
一、条件控制结构
Python 中的条件控制结构主要包括 if
、elif
和 else
语句,此外还有 while
和 for
循环控制流以及与之配合的跳转控制语句 break
、continue
、pass
。
if
语句
if
语句用于根据某个条件的真假来决定是否执行某段代码。如果条件为真(True
),则执行代码块;如果为假(False
),则跳过代码块。
基本语法:
if condition:
# 执行的代码
案例
py
age = 18
if age >= 18:
print("You are an adult.")
输出:
You are an adult.
else
语句
else
语句与 if
语句搭配使用,用于在 if
条件不成立时执行某些操作。它是 if
语句的备选方案。
基本语法:
if condition:
# 执行的代码
else:
# 执行的代码(当条件不成立时)
案例
py
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
输出:
You are a minor.
elif
语句
elif
语句是 else if
的缩写,用于在多个条件中选择执行的代码。可以有多个 elif
语句,并且只有第一个满足条件的 elif
语句会被执行。
基本语法:
py
if condition1:
# 执行的代码块1
elif condition2:
# 执行的代码块2
else:
# 执行的代码块3
流程图
True False True False Start condition1? 代码块1 condition2? 代码块2 代码块3 End
- 从开始节点进入条件判断
- 首先检查 condition1,如果为真则执行对应的代码块
- 如果 condition1 为假,则检查 condition2
- 如果 condition2 为真则执行对应的代码块
- 如果所有条件都为假,则执行 else 代码块
综合案例:判断学生成绩
以下是一个综合案例,结合了 if
、elif
和 else
,判断学生成绩并给出评级。
py
score = int(input("Enter the student's score: "))
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
嵌套条件语句
条件语句可以嵌套使用,这意味着可以在 if
、elif
和 else
语句内部再写条件语句。这样可以处理更加复杂的逻辑。
案例
py
age = 20
has_id = True
if age >= 18:
if has_id:
print("You can vote.")
else:
print("You need an ID to vote.")
else:
print("You are not old enough to vote.")
输出:
You can vote.
每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块
使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块
match...case
在 Python 中没有 switch...case 语句,match...case是 Python 3.10 引入的结构模式匹配功能,不需要再使用一连串的 if-else 来判断。
match 后的对象会依次与 case 后的内容进行匹配,如果匹配成功,则执行匹配到的表达式,否则直接跳过,_ 可以匹配一切。
py
def http_status(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Internal Server Error"
case _:
return "Unknown status"
print(http_status(200)) # OK
print(http_status(404)) # Not Found
case _: 类似于 C 中的 default:,当其他 case 都无法匹配时,匹配这条,保证永远会匹配成功。
条件表达式(三元运算符)
Python 还提供了一个简洁的条件表达式(三元运算符),用于根据条件判断返回不同的值。
语法:
value_if_true if condition else value_if_false
案例
py
python
# 传统 if-else 写法
age = 20
if age >= 18:
status = "成年人"
else:
status = "未成年人"
# 三元运算符写法
status = "成年人" if age >= 18 else "未成年人"
print(status) # 输出: 成年人
列表推导式中的三元运算符
python
# 将列表中的负数转换为0
numbers = [1, -2, 3, -4, 5]
filtered_numbers = [x if x >= 0 else 0 for x in numbers]
print(filtered_numbers) # 输出: [1, 0, 3, 0, 5]
# 标记成绩等级
scores = [85, 92, 78, 60, 45]
grades = ["优秀" if s >= 90 else "良好" if s >= 70 else "及格" if s >= 60 else "不及格" for s in scores]
print(grades) # 输出: ['良好', '优秀', '良好', '及格', '不及格']
二、循环语句
while 循环
while
循环会根据条件重复执行代码块,直到条件为假。可以用于处理重复性任务。
基本语法:
while condition:
# 执行的代码
示例:
py
count = 1
while count <= 5:
print(count)
count += 1
无限循环
对于一个实时请求处理的服务器端。服务器需要持续监听客户端的请求,并对每个请求进行处理。这里需要使用无限循环来保持服务器一直运行
使用 CTRL+C 来退出当前的无限循环
py
def server_main_loop(self):
"""服务器主循环(无限循环)"""
logger.info("服务器主循环开始运行")
self.start_time = datetime.now()
maintenance_counter = 0
while self.running: # 无限循环条件
try:
# 定期维护任务
maintenance_counter += 1
if maintenance_counter >= 30:
self.perform_maintenance()
maintenance_counter = 0
# 避免CPU占用过高
time.sleep(1)
except KeyboardInterrupt:
self.running = False # 退出循环的条件
except Exception as e:
logger.error(f"服务器主循环出错: {e}")
while...else语句
在Python中,while循环可以有一个可选的else块。else块在循环正常结束时执行,即当循环条件变为False时执行。但是,如果循环是通过break语句终止的,else块将不会执行
基本语法
python
while condition:
# 循环体代码
# 如果遇到 break,则跳过 else
else:
# 当循环正常结束时执行的代码
# (即 condition 变为 False,而不是通过 break 退出)
案例:搜索算法
python
def linear_search(items, target):
"""线性搜索,使用while-else判断是否找到"""
index = 0
while index < len(items):
if items[index] == target:
print(f"在位置 {index} 找到目标值 {target}")
break
index += 1
else:
print(f"在列表中未找到目标值 {target}")
return index if index < len(items) else -1
# 测试搜索
numbers = [10, 20, 30, 40, 50]
linear_search(numbers, 30) # 输出: 在位置 2 找到目标值 30
linear_search(numbers, 35) # 输出: 在列表中未找到目标值 35
for 循环
for
循环用于遍历一个可迭代对象(如列表、字符串、字典等),并对每个元素执行代码块。
基本语法:
for variable in iterable:
# 执行的代码
案例
py
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
for...else语句
for...else 语句用于在循环结束后执行一段代码,如果在循环过程中遇到了 break 语句,则会中断循环,此时不会执行 else 子句。
三、循环控制
break语句
break
语句用于终止当前的循环(for
或 while
),并跳出循环。它通常用于提前退出循环。
案例
py
count = 0
while count < 5:
if count == 3:
break # 当 count 为 3 时退出循环
print(count)
count += 1
continue语句
continue
语句用于跳过当前循环中的剩余代码,并立即开始下一次迭代。它不会终止循环,而是跳过本次循环,进入下一次循环。
案例
py
for i in range(5):
if i == 3:
continue # 跳过当 i 为 3 时的打印
print(i)
pass 语句
pass
语句是一个空语句,它通常用于占位符,表示"什么都不做"。它在某些地方语法上需要一个语句,但程序上并不需要做任何事情时非常有用。
py
def placeholder_function():
pass # 这里以后可以添加实现代码