## 1、分支结构–if语句

1）分支语句模板

``````if 条件:
代码块
elif 条件:
代码块
...
else:
代码块
``````

2）分支语句例子

``````age = 18
res = 0  # 变量初始化
if age >22:
print('可以结婚了’）
elif age>30:
print('赶紧结婚')
else:
print('再等等吧')
``````

3）嵌套语句：if语句中有if

``````age = eval(input("请输入年龄"))
if age > 18:
is_public_place = bool(eval(input("公共场合输入1，非公共场合输入0")))
if not is_public_place:
print("可以抽烟")
else:
print("禁止抽烟")
else:
print("禁止抽烟")
``````

## 2、遍历循环–for循环

1）for循环模板

``````for 元素 in 可迭代对象: # 可迭代对象包括列表/元组/字符串/字典
执行语句
``````

2）for循环例子
① 直接迭代

``````graduates = ("lilei","hanmeimei","Jim")
``````

② 变换迭代

``````students = {201901:'小明',201902:'小红',201903:'小强'}
for k,v in students.items():
print(k,v)
# 201901 小明
# 201902 小红
# 201903 小强
for student in students:
print(student)
# 201901
# 201902
# 201903
``````

③ range()对象

``````res = []
for i in range(1,10,2): # 左闭右开，每个+2，1/3/5/7/9
res.append(i**2)
print(res) # [1,9,25,49,81]
``````

3）break和continue
① break用于结束整个循环

``````product_scores = [89,90,99,70,67,78,85,92,77,82]
i = 0
for score in product_scores:
# 如果低于75的个数超过1个，则不合格
if score < 75:
i += 1
if i == 2:
print("产品不合格")
break  # 结束了整个循环，67后面的元素就遍历不到了
``````

② continue用于结束本次循环

``````product_scores = [89,90,99,70,67,78,85,92,77,82]
for i in range(len(product_scores)):
# 如果低于75，输出警告
if product_scores[i]>=75:
continue
print("第{0}个产品，分数为{1},不合格".format(i,product_scores[i]))
``````

4）for与else的配合

``````product_scores = [89,90,99,70,67,78,85,92,77,82]
i = 0
for score in product_scores:
if score < 75:
i += 1
if i == 2:
print("产品不合格")
break
else:  # for遍历完之后，如果没有break，则运行else
print("产品合格")
``````

## 3、无限循环–while循环

1）while的一般格式

``````while 判断条件:
执行语句
# 条件为真，执行语句
# 条件为假，while循环结束
``````

2）不用while