age = 18 res = 0 # 变量初始化 if age >22: print('可以结婚了’) elif age>30: print('赶紧结婚') else: print('再等等吧')
3)嵌套语句:if语句中有if
1 2 3 4 5 6 7 8 9
age = eval(input("请输入年龄")) if age > 18: is_public_place = bool(eval(input("公共场合输入1,非公共场合输入0"))) ifnot is_public_place: print("可以抽烟") else: print("禁止抽烟") else: print("禁止抽烟")
2、遍历循环–for循环
1)for循环模板
1 2
for 元素 in 可迭代对象: # 可迭代对象包括列表/元组/字符串/字典 执行语句
2)for循环例子 ① 直接迭代
1 2 3
graduates = ("lilei","hanmeimei","Jim") for graduate in graduates: print("Congratulations, " + graduate)
② 变换迭代
1 2 3 4 5 6 7 8 9 10 11
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()对象
1 2 3 4
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用于结束整个循环
1 2 3 4 5 6 7 8 9
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用于结束本次循环
1 2 3 4 5 6
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的配合
1 2 3 4 5 6 7 8 9 10
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("产品合格")