第3章 流程控制语句
- 3.1 程序结构
- 3.2 选择语句
- 3.3 条件表达式
- 3.4 循环语句
- 3.5 跳转语句
- 3.6 空语句
3.4 循环语句
1、while 循环
# 带else的while循环,循环结束后执行,根据需要取舍else
while 条件表达式:
循环体
else:
语句
a = 0
while a <= 5:
print(a)
a += 1
else:
print("循环已结束")
说明:python中没有do...while语句
2、for 循环
# 常用的循环模式
for 迭代变量 in 对象:
循环体
# 带else的循环模式,循环结束后执行
for 迭代变量 in 对象:
循环体
else:
语句
# 从列表中按顺序一个一个地取出值
list1 = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
for wday in list1:
print(wday)
# 从字典中取出键、值、键值对
dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
for key in dict1.keys():
print(key)
for value in dict1.values():
print(value)
for item in dict1.items():
print(item)
# 利用range()创建列表
list1 = []
for i in range(3):
list1.append(i)
print(list1)