完整的for循环
for num in (1,2,3):
print(num)
if num == 2:
break
else:
# 如果循环体内部使用break退出循环
# else 下方的代码
print("会执行么?") # 不会执行
print("循环结束")
输出为
for else搜索字典列表
students = [
{"name":"小美"},
{"name":"阿土"}
]
# 在学员列表中搜索指定的姓名
find_name = "张三"
for stu_dict in students:
print(stu_dict)
if stu_dict["name"] == find_name:
print("找到了 %s" % find_name)
# 如果已经找到,应该直接退出循环,而不再遍历后续的元素
break
else:
# 如果希望在搜索列表时,所有的字典检查之后,都没有发现需要搜索的目标
# 还需要得到一个统一的提示
print("抱歉没有找到 %s" % find_name)
print("循环结束")
输出为