Python学习历程:核心控制结构与代码组织
Python作为一门简洁高效的编程语言,其核心控制结构(如for、if、while)是构建程序逻辑的基础。以下从实际应用角度分析这些结构的典型用法与组织方式,配合代码示例说明如何高效组合这些结构。
基础条件控制:if语句
if语句用于实现条件分支,通过布尔表达式决定代码执行路径。Python支持if-elif-else的多级嵌套。
# 示例:成绩分级系统
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B") # 输出B
elif score >= 70:
print("C")
else:
print("D")
嵌套if时需注意缩进层级:
age = 25
has_license = True
if age >= 18:
if has_license:
print("可以驾驶")
else:
print("需考取驾照")
else:
print("年龄不足")
循环结构:for与while
for循环通常用于遍历序列(如列表、字符串),而while循环适合条件不确定的场景。
for循环遍历集合元素:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit.upper()) # 输出APPLE, BANANA, CHERRY
# 配合range()控制循环次数
for i in range(3): # 生成0,1,2
print(f"第{i+1}次迭代")
while循环处理动态条件:
countdown = 5
while countdown > 0:
print(countdown)
countdown -= 1 # 修改条件变量
print("发射!")
Python学习历程:核心控制结构与代码组织
Python作为一门简洁高效的编程语言,其核心控制结构(如for、if、while)是构建程序逻辑的基础。以下从实际应用角度分析这些结构的典型用法与组织方式,配合代码示例说明如何高效组合这些结构。
基础条件控制:if语句
if语句用于实现条件分支,通过布尔表达式决定代码执行路径。Python支持if-elif-else的多级嵌套。
# 示例:成绩分级系统
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B") # 输出B
elif score >= 70:
print("C")
else:
print("D")
嵌套if时需注意缩进层级:
age = 25
has_license = True
if age >= 18:
if has_license:
print("可以驾驶")
else:
print("需考取驾照")
else:
print("年龄不足")
循环结构:for与while
for循环通常用于遍历序列(如列表、字符串),而while循环适合条件不确定的场景。
for循环遍历集合元素:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit.upper()) # 输出APPLE, BANANA, CHERRY
# 配合range()控制循环次数
for i in range(3): # 生成0,1,2
print(f"第{i+1}次迭代")
while循环处理动态条件:
countdown = 5
while countdown > 0:
print(countdown)
countdown -= 1 # 修改条件变量
print("发射!")
。&spm=1001.2101.3001.5002&articleId=153142332&d=1&t=3&u=2c0c7887790041eca8aaa9d494630bb3)
1216

被折叠的 条评论
为什么被折叠?



