一、分支结构
单分支结构
if<条件>:
<语句块>
二分支结构
if<条件>:
<语句块>
else:
<语句块>
紧凑形式:“对” if guess==99 else “错”
多分支结构
if<条件>:
<语句块>
elif<条件>:
<语句块>
else:
<语句块>
二、循环结构
遍历循环
for<循环变量> in <遍历结构>:
<语句块>
1.计数循环:
for i in range(N):
<语句块>
例如:for i in range(5):
print(i)------------0,1,2,3,4
例如:for i in range(1,6):
print(i)-----------1,2,3,4,5
2. 字符串遍历循环:
for c in s:
<语句块>
例如:for c in “Python”:
print(c,end=",")-----P,y,t,h,o,n
3.列表遍历循环:
for item in ls:
<语句块>
例如:for item in[1,“hel”,2]:
print(item,end=",")--------1,hel,2
4.文件遍历循环:
for line in fi :
<语句块>-----遍历文件的每一行
无限循环
while <条件>:
<语句块>
例如:a=3
while a>0:
a=a-1
print(a)------2,1,0
若程序执行陷入无限循环中,可用CTRL+c退出
循环控制保留字
break :跳出并结束当前整个循环,执行循环后的语句
continue:结束当次循环,继续执行后续次数循环
例1: for c in “Python”:
if c==‘t’:
continue
print(c,end="")------Pyhon
例2 : for c in “Python”:
if c==‘t’:
break
print(c,end="")------Py
循环与else的搭配
for <循环变量> in <遍历结构>:
<语句块1>
else:
<语句块2>
while<条件>:
<语句块1>
else:
<语句块2>
例一: for c in “Python”:
if c==‘t’:
continue
print(c,end="")
else:
print(“正常退出”)------Pyhon正常退出
例二:for c in “Python”:
if c==‘t’:
break
print(c,end="")
else:
print(“正常退出”)------Py