分支结构
-
单分支
# if一般用于判断/选择的场景 # 90以上优秀 score = 95 if score > 90: print('优秀')# 双分支
-
双分支
# if...else # 90以上优秀,90一下良好 score = 95 if score > 90: print('优秀') else: print('良好')
-
多分支
# if...elif...elif...else # if...if...if...if # 90以上优秀,90-70良好,70以下不及格 score = 95 if score > 90: print('优秀') elif score > 70: print('良好') else: print('及格') score = 95 if score > 90: print('优秀') if score > 70 and score < 90: # 同时满足 print('良好') if score < 60: print('及格')
循环
for循环
# 举例
for i in range(100): # 循环100次
print(i)
range(5) # [0,1,2,3,4]
range(1,3) # [1,2]
range(1,10,2) # [1,3,5,7,9]
for i in 'nick': # 也可以循环输出字符串
print(i)
while循环
count = 0
while count < 100:
count += 1
print(count)
while...else
count = 0
while count < 100:
count += 1
print(count)
else: #正常跳出循环的时候会执行,异常中断循环不执行
print('打我')
continue + break
##演示continue语法##
count = 0
while count < 100:
count += 1
if count == 50:
continue # 不执行下面代码,直接开始下次循环
print(count)
##演示break语法##
count = 0
while count < 100:
count += 1
if count == 50:
break # 跳出并终止循环
print(count)