控制流程
学习Python的条件语句、循环和迭代工具
20%
条件语句
循环语句
迭代工具
练习例题
条件语句
if-elif-else语句
Python使用缩进来组织代码块,条件语句遵循简洁的语法。
# 基本的if语句
x = 10
if x > 0:
print("x是正数")
# if-else语句
y = -5
if y > 0:
print("y是正数")
else:
print("y是负数或零")
# if-elif-else语句
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"成绩: {grade}") # 成绩: B
# 嵌套条件语句
num = 15
if num > 0:
if num % 2 == 0:
print("正偶数")
else:
print("正奇数")
else:
if num < 0:
print("负数")
else:
print("零")
条件表达式
Python支持简洁的条件表达式(三元运算符)。
# 三元表达式
age = 20
status = "成年" if age >= 18 else "未成年"
print(status) # 成年
# 嵌套三元表达式(尽量避免使用,影响可读性)
score = 85
grade = "A" if score >= 90 else ("B" if score >= 80 else ("C" if score >= 70 else "D"))
print(grade) # B
# 使用三元表达式给变量赋值
x = 10
y = 20
max_value = x if x > y else y
print(max_value) # 20
# 在列表推导式中使用条件表达式
numbers = [1, 2, 3, 4, 5]
result = ["偶数" if n % 2 == 0 else "奇数" for n in numbers]
print(result) # ['奇数', '偶数', '奇数', '偶数', '奇数']
真值测试
Python中任何对象都可以进行真值测试,以下值被视为False:
# 被视为False的值
print(bool(None)) # False
print(bool(False)) # False
print(bool(0)) # False
print(bool(0.0)) # False
print(bool('')) # False - 空字符串
print(bool([])) # False - 空列表
print(bool(())) # False - 空元组
print(bool({})) # False - 空字典
print(bool(set())) # False - 空集合
# 其他所有值视为True
print(bool(1)) # True
print(bool(-1)) # True
print(bool('hello')) # True
print(bool([0])) # True - 非空列表,即使包含False的值
print(bool((None,))) # True - 非空元组,即使包含False的值
# 在if语句中使用真值测试
name = ""
if name:
print("名字不为空")
else:
print("名字为空") # 名字为空
numbers = [1, 2, 3]
if numbers:
print("列表不为空") # 列表不为空
# 使用and和or的短路特性
print(0 and 'hello') # 0 (第一个操作数为假,不会计算第二个)
print(1 and 'hello') # 'hello' (第一个为真,返回第二个值)
print(0 or 'hello') # 'hello' (第一个为假,返回第二个值)
print(1 or 'hello') # 1 (第一个为真,不会计算第二个)
- 使用缩进代替大括号来划分代码块
- 支持elif关键字用于多分支条件
- 条件表达式格式为:value_if_true if condition else value_if_false
- Python使用短路逻辑评估布尔表达式