跳到主要内容Python 流程控制 | 极客日志Python算法
Python 流程控制
Python 流程控制的核心语法,包括条件判断(if/elif/else)、循环结构(while/for)以及循环控制语句(break/continue/pass)。内容涵盖关系运算符、三元表达式、嵌套逻辑、字符串格式化输出等知识点,并通过猜数字游戏、学生成绩管理系统等综合案例演示了实际应用。文章还提供了常见错误排查与最佳实践建议,帮助读者掌握 Python 基础编程逻辑。
赛博朋克1 浏览 一、if 条件语句
1. 条件表达式与关系运算符
关系运算符(比较运算符)
| 运算符 | 含义 | 示例 | 结果 |
|---|
== | 等于 | 5 == 5 | True |
!= |
a = 10
b = 20
print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= 10)
print(a <= 5)
print("apple" < "banana")
print("Hello" == "hello")
2. if 语句的基本结构
if 条件表达式:
age = 18
if age >= 18:
print("您已成年")
print("可以进入网吧")
if True:
print("这条会执行")
print("这也是 if 块内的")
print("这是 if 块外的")
3. if-else 条件语句
if 条件表达式:
else:
num = 7
if num % 2 == 0:
print(f"{num}是偶数")
else:
print(f"{num}是奇数")
age = 15
if age >= 18:
print("已成年,可以考驾照")
else:
print(f"未成年,还需{18-age}年才能考驾照")
age = 20
status = "成年" if age >= 18 else "未成年"
print(f"状态:{status}")
if age >= 18:
status = "成年"
else:
status = "未成年"
4. 多重 if 语句(if-elif-else)
if 条件 1:
elif 条件 2:
elif 条件 3:
...
else:
score = 85
if score >= 90:
grade = 'A'
print("优秀!")
elif score >= 80:
grade = 'B'
print("良好!")
elif score >= 70:
grade = 'C'
print("中等!")
elif score >= 60:
grade = 'D'
print("及格!")
else:
grade = 'F'
print("不及格,继续努力!")
print(f"成绩等级:{grade}")
month = 7
if 3 <= month <= 5:
season = "春季"
elif 6 <= month <= 8:
season = "夏季"
elif 9 <= month <= 11:
season = "秋季"
else:
season = "冬季"
print(f"{month}月是{season}")
height = 1.75
weight = 70
bmi = weight / (height ** 2)
print(f"BMI 指数:{bmi:.1f}")
if bmi < 18.5:
result = "偏瘦"
elif bmi < 24:
result = "正常"
elif bmi < 28:
result = "偏胖"
else:
result = "肥胖"
print(f"身体状况:{result}")
5. if 语句嵌套
age = 25
has_id = True
has_ticket = True
if age >= 18:
print("已成年")
if has_id:
print("有身份证")
if has_ticket:
print("可以进入会场")
else:
print("没有门票,不能进入")
else:
print("没有身份证,不能进入")
else:
print("未成年,不能进入")
username = input("请输入用户名:")
password = input("请输入密码:")
if username:
if len(username) >= 3:
if password == "123456":
print("登录成功!")
else:
print("密码错误!")
else:
print("用户名长度至少 3 位")
else:
print("用户名不能为空")
if username and len(username) >= 3 and password == "123456":
print("登录成功!")
else:
print("登录失败!")
6. if 语句的常见问题
if True:
print("正确缩进")
print("缩进不一致")
if name:
print(f"Hello, {name}")
else:
print("名字为空")
age = 25
city = "北京"
if age >= 18 and city == "北京":
print("符合条件的北京成年人")
二、Python 的循环
1. while 循环语句
while 条件表达式:
count = 1
while count <= 5:
print(f"第{count}次循环")
count += 1
sum_val = 0
i = 1
while i <= 100:
sum_val += i
i += 1
print(f"1 到 100 的和:{sum_val}")
import random
secret = random.randint(1, 100)
guess = 0
attempts = 0
while guess != secret:
guess = int(input("猜一个数字 (1-100):"))
attempts += 1
if guess < secret:
print("猜小了")
elif guess > secret:
print("猜大了")
print(f"恭喜猜对了!数字是{secret},猜了{attempts}次")
2. Python 注释
"""模块文档字符串:这个模块演示 Python 的各种注释方式
可以写多行,通常放在文件开头
"""
print("Hello")
''' 这也是多行注释
使用三个单引号
但通常用双引号作为文档字符串
'''
def example_function():
"""函数文档字符串
说明函数的功能、参数、返回值等
"""
pass
class MyClass:
"""类的文档字符串
说明类的用途和使用方法
"""
pass
3. 字符串的格式化输出
name = "张三"
age = 25
score = 85.5
print("姓名:%s,年龄:%d,成绩:%.1f" % (name, age, score))
print("姓名:{},年龄:{},成绩:{}".format(name, age, score))
print("姓名:{0},年龄:{1},成绩:{2}".format(name, age, score))
print("姓名:{name},年龄:{age},成绩:{score}".format(
name=name, age=age, score=score
))
print(f"姓名:{name},年龄:{age},成绩:{score}")
print(f"成绩保留两位小数:{score:.2f}")
print(f"姓名:{name.upper()}")
num = 1234.56789
print(f"默认:{num}")
print(f"保留 2 位小数:{num:.2f}")
print(f"科学计数法:{num:.2e}")
print(f"百分比:{0.856:.2%}")
print(f"左对齐 10 位:{name:<10}")
print(f"右对齐 10 位:{name:>10}")
print(f"居中 10 位:{name:^10}")
print(f"填充 0:{123:08d}")
a, b = 10, 20
print(f"{a} + {b} = {a + b}")
print(f"{a} * {b} = {a * b}")
4. while 循环嵌套
i = 1
while i <= 9:
j = 1
while j <= i:
print(f"{j}×{i}={i*j:2d}", end="")
j += 1
print()
i += 1
row = 1
while row <= 5:
col = 1
while col <= row:
print("*", end="")
col += 1
print()
row += 1
row = 5
while row >= 1:
col = 1
while col <= row:
print("*", end="")
col += 1
print()
row -= 1
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
i = 0
while i < len(matrix):
j = 0
while j < len(matrix[i]):
print(f"{matrix[i][j]:3d}", end="")
j += 1
print()
i += 1
三、for 循环
1. for 循环的几种方式
for item in [1, 2, 3, 4, 5]:
print(item)
for char in "Python":
print(char)
for i in range(5):
print(i)
for i in range(2, 6):
print(i)
for i in range(1, 10, 2):
print(i)
for i in range(10, 0, -1):
print(i)
fruits = ["苹果", "香蕉", "橙子"]
for index, fruit in enumerate(fruits):
print(f"索引{index}: {fruit}")
person = {"name": "张三", "age": 25, "city": "北京"}
for key in person:
print(f"{key}: {person[key]}")
for value in person.values():
print(value)
for key, value in person.items():
print(f"{key}: {value}")
2. for 循环示例
sum_val = 0
for i in range(1, 101):
sum_val += i
print(f"1 到 100 的和:{sum_val}")
numbers = [23, 45, 12, 67, 34, 89, 56]
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
print(f"最大值:{max_num}")
text = "Hello Python Programming"
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
print(f"元音字母个数:{count}")
squares = [x**2 for x in range(10)]
print(f"平方列表:{squares}")
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(f"偶数的平方:{even_squares}")
sales = [1200, 3400, 2800, 3900, 4500]
total = 0
for sale in sales:
total += sale
average = total / len(sales)
print(f"总销售额:{total}")
print(f"平均销售额:{average:.0f}")
3. 逻辑运算符
age = 25
has_id = True
if age >= 18 and has_id:
print("可以进入")
is_student = True
is_teacher = False
if is_student or is_teacher:
print("可以享受优惠")
is_weekend = False
if not is_weekend:
print("今天是工作日")
def test():
print("test 函数被执行")
return True
if False and test():
print("不会执行")
if True or test():
print("test 不会被执行")
a, b, c = True, False, True
result1 = a and b or c
result2 = (a and b) or c
print(result1, result2)
score = 85
attendance = 90
homework_done = True
if score >= 80 and attendance >= 80 and homework_done:
print("成绩合格")
elif score >= 70 and (attendance >= 90 or homework_done):
print("成绩基本合格")
else:
print("需要补考")
4. for 循环嵌套
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}×{i}={i*j:2d}", end="")
print()
for i in range(1, 10):
for j in range(1, 10):
if j <= i:
print(f"{j}×{i}={i*j:2d}", end="")
print()
for i in range(1, 6):
for j in range(i):
print("*", end="")
print()
n = 5
for i in range(n):
print(" " * (n - i - 1) + "*" * (2 * i + 1))
for i in range(n - 2, -1, -1):
print(" " * (n - i - 1) + "*" * (2 * i + 1))
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for col in row:
print(f"{col:3d}", end="")
print()
total = 0
for row in matrix:
for col in row:
total += col
print(f"所有元素之和:{total}")
transposed = []
for i in range(len(matrix[0])):
row = []
for j in range(len(matrix)):
row.append(matrix[j][i])
transposed.append(row)
print("转置后的矩阵:")
for row in transposed:
print(row)
numbers = [1, 3, 5, 2, 3, 4, 5, 6, 7, 5]
duplicates = []
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
if numbers[i] == numbers[j] and numbers[i] not in duplicates:
duplicates.append(numbers[i])
print(f"重复元素:{duplicates}")
四、循环控制
1. break 语句
numbers = [1, 3, 5, 7, 8, 9, 11]
for num in numbers:
if num % 2 == 0:
print(f"找到第一个偶数:{num}")
break
print(f"检查{num},不是偶数")
else:
print("没有找到偶数")
password = "123456"
attempts = 0
max_attempts = 3
while attempts < max_attempts:
user_input = input("请输入密码:")
attempts += 1
if user_input == password:
print("登录成功!")
break
else:
print(f"密码错误,还剩{max_attempts - attempts}次机会")
else:
print(f"已尝试{max_attempts}次,账户被锁定")
for i in range(5):
for j in range(5):
if i * j > 6:
print(f"i={i}, j={j},乘积大于 6,退出内层循环")
break
print(f"i={i}, j={j}, 乘积={i*j}")
print(f"外层循环继续 i={i}")
found = False
for i in range(5):
for j in range(5):
if i == 2 and j == 3:
print(f"找到目标:i={i}, j={j}")
found = True
break
if found:
break
2. continue 语句
print("1-10 中的奇数:")
for i in range(1, 11):
if i % 2 == 0:
continue
print(i, end=" ")
print()
numbers = [10, -5, 20, -8, 30, 15, -3]
print("正数:")
for num in numbers:
if num < 0:
continue
print(num, end=" ")
print()
text = "Hello, Python Programming!"
result = ""
for char in text:
if char in ",! ":
continue
result += char
print(f"原字符串:{text}")
print(f"处理后:{result}")
i = 0
while i < 10:
i += 1
if i % 3 == 0:
continue
print(i, end=" ")
print()
valid_inputs = []
while len(valid_inputs) < 3:
user_input = input(f"请输入第{len(valid_inputs)+1}个有效数字:")
if not user_input.isdigit():
print("输入无效,请输入数字")
continue
num = int(user_input)
if num < 1 or num > 100:
print("数字必须在 1-100 之间")
continue
valid_inputs.append(num)
print(f"已添加,当前有效输入:{valid_inputs}")
print(f"收集完成:{valid_inputs}")
3. break 和 continue 对比
print("break 示例:找到第一个负数后停止")
numbers = [3, 6, 1, -2, 8, -5, 9]
for num in numbers:
if num < 0:
print(f"找到负数{num},停止循环")
break
print(f"处理正数:{num}")
print("\n" + "="*30)
print("continue 示例:跳过所有负数")
for num in numbers:
if num < 0:
print(f"跳过负数{num}")
continue
print(f"处理正数:{num}")
def show_menu():
"""显示菜单并处理用户选择"""
while True:
print("\n=== 菜单 ===")
print("1. 查看信息")
print("2. 添加信息")
print("3. 删除信息")
print("4. 退出")
choice = input("请选择 (1-4):")
if choice == "1":
print("查看信息功能")
elif choice == "2":
print("添加信息功能")
elif choice == "3":
print("删除信息功能")
elif choice == "4":
print("感谢使用,再见!")
break
else:
print("输入错误,请重新选择")
continue
print("\n" + "="*30)
print("循环的 else 子句示例:")
def find_element(lst, target):
for item in lst:
if item == target:
print(f"找到目标:{target}")
break
else:
print(f"未找到目标:{target}")
find_element([1, 2, 3, 4, 5], 3)
find_element([1, 2, 3, 4, 5], 10)
count = 1
while count <= 3:
print(f"第{count}次循环")
if count == 2:
print("遇到 2,但继续")
count += 1
else:
print("循环正常结束")
4. pass 语句
age = 20
if age >= 18:
pass
else:
print("未成年")
def not_implemented_yet():
"""这个函数还没实现"""
pass
class MyClass:
def method1(self):
pass
def method2(self):
pass
for i in range(5):
if i == 2:
pass
else:
print(i)
for i in range(5):
if i == 2:
pass
print("这是 pass 后的打印")
print(f"i={i}")
print("--- 对比 ---")
for i in range(5):
if i == 2:
continue
print("这行不会执行")
print(f"i={i}")
五、综合应用案例
案例 1:猜数字游戏(增强版)
import random
def guess_number_game():
"""猜数字游戏,包含难度选择和计分系统"""
print("欢迎来到猜数字游戏!")
while True:
print("\n请选择难度:")
print("1. 简单(1-50,10 次机会)")
print("2. 中等(1-100,7 次机会)")
print("3. 困难(1-200,5 次机会)")
choice = input("请输入数字选择 (1-3):")
if choice == "1":
max_num = 50
max_attempts = 10
break
elif choice == "2":
max_num = 100
max_attempts = 7
break
elif choice == "3":
max_num = 200
max_attempts = 5
break
else:
print("输入错误,请重新选择")
continue
play_again = True
total_games = 0
total_attempts = 0
while play_again:
secret = random.randint(1, max_num)
attempts = 0
guessed = False
print(f"\n游戏开始!数字在 1-{max_num}之间,你有{max_attempts}次机会")
while attempts < max_attempts:
try:
guess = int(input(f"还剩{max_attempts-attempts}次机会,请输入:"))
attempts += 1
if guess < 1 or guess > max_num:
print(f"请输入 1-{max_num}之间的数字")
attempts -= 1
continue
if guess < secret:
print("猜小了")
elif guess > secret:
print("猜大了")
else:
print(f"恭喜!猜对了!用了{attempts}次机会")
guessed = True
break
except ValueError:
print("请输入有效的数字")
attempts -= 1
if not guessed:
print(f"很遗憾,机会用完了。正确答案是{secret}")
total_games += 1
total_attempts += attempts
while True:
again = input("再玩一局?(y/n):").lower()
if again == 'y':
break
elif again == 'n':
play_again = False
break
else:
print("请输入 y 或 n")
if total_games > 0:
print(f"\n游戏结束!共玩{total_games}局,平均每局猜{total_attempts/total_games:.1f}次")
案例 2:学生成绩管理系统
def student_score_system():
"""简单的学生成绩管理系统"""
students = []
while True:
print("\n" + "="*40)
print("学生成绩管理系统")
print("="*40)
print("1. 添加学生成绩")
print("2. 查看所有学生")
print("3. 统计成绩")
print("4. 查询学生")
print("5. 删除学生")
print("6. 退出")
print("-"*40)
choice = input("请选择操作 (1-6):")
if choice == "1":
print("\n--- 添加学生 ---")
name = input("请输入姓名:")
name_exists = False
for student in students:
if student["name"] == name:
name_exists = True
break
if name_exists:
print("该学生已存在!")
continue
scores = []
subjects = ["语文", "数学", "英语"]
for subject in subjects:
while True:
try:
score = float(input(f"请输入{subject}成绩:"))
if 0 <= score <= 100:
scores.append(score)
break
else:
print("成绩必须在 0-100 之间")
except ValueError:
print("请输入有效的数字")
avg_score = sum(scores) / len(scores)
students.append({
"name": name,
"scores": scores,
"avg": avg_score
})
print(f"学生{name}添加成功!")
elif choice == "2":
print("\n--- 学生列表 ---")
if not students:
print("暂无学生信息")
continue
print(f"{'姓名':<10}{'语文':<8}{'数学':<8}{'英语':<8}{'平均分':<8}")
print("-"*42)
for student in students:
print(f"{student['name']:<10}", end="")
for score in student['scores']:
print(f"{score:<8}", end="")
print(f"{student['avg']:<8.1f}")
elif choice == "3":
print("\n--- 成绩统计 ---")
if not students:
print("暂无学生信息")
continue
subjects = ["语文", "数学", "英语"]
subject_scores = [[], [], []]
for student in students:
for i in range(3):
subject_scores[i].append(student['scores'][i])
for i, subject in enumerate(subjects):
scores = subject_scores[i]
print(f"\n{subject}:")
print(f" 最高分:{max(scores)}")
print(f" 最低分:{min(scores)}")
print(f" 平均分:{sum(scores)/len(scores):.1f}")
all_scores = []
for student in students:
all_scores.extend(student['scores'])
print(f"\n总体:")
print(f" 学生人数:{len(students)}")
print(f" 总分最高:{max(all_scores)}")
print(f" 总分最低:{min(all_scores)}")
print(f" 总平均分:{sum(all_scores)/len(all_scores):.1f}")
elif choice == "4":
print("\n--- 查询学生 ---")
name = input("请输入要查询的学生姓名:")
found = False
for student in students:
if student['name'] == name:
print(f"\n姓名:{student['name']}")
subjects = ["语文", "数学", "英语"]
for i, score in enumerate(student['scores']):
print(f"{subjects[i]}:{score}")
print(f"平均分:{student['avg']:.1f}")
if student['avg'] >= 90:
print("评级:优秀")
elif student['avg'] >= 80:
print("评级:良好")
elif student['avg'] >= 70:
print("评级:中等")
elif student['avg'] >= 60:
print("评级:及格")
else:
print("评级:不及格")
found = True
break
if not found:
print(f"未找到学生:{name}")
elif choice == "5":
print("\n--- 删除学生 ---")
name = input("请输入要删除的学生姓名:")
for i, student in enumerate(students):
if student['name'] == name:
confirm = input(f"确定要删除学生{name}吗?(y/n):")
if confirm.lower() == 'y':
students.pop(i)
print("删除成功!")
else:
print("已取消删除")
break
else:
print(f"未找到学生:{name}")
elif choice == "6":
print("感谢使用,再见!")
break
else:
print("输入错误,请重新选择")
continue
案例 3:猜单词游戏
import random
def word_guess_game():
"""猜单词游戏"""
words = {
"python": "一种编程语言",
"linux": "操作系统",
"apple": "水果/科技公司",
"computer": "电子设备",
"programming": "编写代码的过程",
"database": "数据存储系统",
"network": "计算机网络",
"algorithm": "解决问题的方法"
}
print("欢迎来到猜单词游戏!")
print("="*40)
score = 0
total_questions = 0
while True:
word, hint = random.choice(list(words.items()))
scrambled = list(word)
random.shuffle(scrambled)
scrambled_str = "".join(scrambled)
print(f"\n第{total_questions+1}题")
print(f"提示:{hint}")
print(f"打乱的字母:{scrambled_str}")
attempts = 0
max_attempts = 3
while attempts < max_attempts:
guess = input(f"请输入你的答案(还剩{max_attempts-attempts}次机会):").lower()
attempts += 1
if guess == word:
print("✓ 正确!")
score += 1
break
else:
if attempts < max_attempts:
print("✗ 不对,再试试")
else:
print(f"很遗憾,正确答案是:{word}")
total_questions += 1
while True:
play_again = input("\n继续游戏?(y/n):").lower()
if play_again == 'y':
break
elif play_again == 'n':
print(f"\n游戏结束!")
print(f"答题总数:{total_questions}")
print(f"答对题数:{score}")
print(f"正确率:{score/total_questions*100:.1f}%")
return
else:
print("请输入 y 或 n")
六、总结
1. 流程控制要点
| 控制结构 | 关键字 | 用途 |
|---|
| 条件判断 | if, elif, else | 根据条件执行不同代码块 |
| 循环 | while, for | 重复执行代码块 |
| 循环控制 | break, continue | 中断或跳过循环 |
| 占位符 | pass | 空语句,语法占位 |
2. 循环选择建议
while True:
password = input("请输入密码:")
if password == "123456":
break
for item in [1, 2, 3, 4, 5]:
print(item)
for i in range(10):
print(i)
3. 常见错误和最佳实践
i = 1
while i <= 10:
print(i)
i += 1
fruits = ["苹果", "香蕉", "橙子"]
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
for item in items:
if condition:
break
else:
handle_not_found()
if not condition1:
return
if not condition2:
return
if not condition3:
return
do_something()
微信扫一扫,关注极客日志
微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
相关免费在线工具
- 加密/解密文本
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
- curl 转代码
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
- Base64 字符串编码/解码
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
- Base64 文件转换器
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
- Markdown转HTML
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
- HTML转Markdown
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online