控制流
info
代码布局不仅影响可读性,更体现了对代码质量的态度。一致的缩进、适当的空行、合理的行长度,这些细节共同构成了优雅的 Python 代码。
- 使用 4 个空格进行缩进
- 每行不超过 79 个字符
- 用空行分隔顶级函数和类定义
条件判断
条件判断是编程中非常基础且重要的概念,它允许我们根据不同的条件执行不同的代码块。
if, elif, else
if condition:
# 当条件为真时执行的代码块
elif condition:
# 当条件为假时执行的代码块
else:
# 当条件都不满足时执行的代码块
a = 62
print("exam score check:")
if a >= 60:
print("student pass")
elif a == 0:
print("student 0: not pass")
else:
print("student not pass")
一个例子
year = 1900
if year % 400 == 0:
print("This is a leap year!")
# 两个条件都满足才执行
elif year % 4 == 0 and year % 100 != 0:
print("This is a leap year!")
else:
print("This is not a leap year.")
# This is not a leap year.
my_list = [1, 2]
# 判断一个列表是否为空。
if len(my_list) > 0:
print("the first element is: ", my_list[0])
else:
print("no element.")
info
三元表达式是一种简洁的条件赋值方式,相当于简化版的 if-else 语句。一行语句实现一个条件赋值。非常 Pythonic。
expression1 if condition else expression2
其中 expression1
和 expression2
可以是任意表达式,condition
是任意条件表达式。
当 condition
为 True 时,返回 expression1
,否则返回 expression2
。
# 下面通过括号(可省)将同个表达式的部分标注了出来,更加可读。
x = -1
y = ("A") if (x > 0) else ("B")
print(y) # B
y = (x + 1) if (x > 0) else (x - 1)
print(y) # -2
# 示例:将负数转为0,正数保持不变
numbers = [-3, -1, 0, 2, 5]
processed = [x if x >= 0 else 0 for x in numbers]
print(processed) # [0, 0, 0, 2, 5]
# 根据条件设置不同的值
scores = [85, 92, 78, 96, 73]
grades = ['A' if score >= 90 else 'B' if score >= 80 else 'C' for score in scores]
print(grades) # ['B', 'A', 'C', 'A', 'C']