while、for循环:break跳出整个循环;continue跳出当前循环,pass无运算占位语句不做任何操作死循环,else正常退出才执行。
while循环和for循环一般格式如下:
while <test1>:
<statements l>
if <test2>: break
if <test3>: continue
else:
<statements 2>
for <target> in <object>:
<statements >
else:
<statements>
while模式:
a="python-learning";
while a:
print(a,end=' '); #end=' '在打印末尾添加空格,未传递print默认未\n换行
a=a[3:]
print("") #换行
a,b=0,20
while a<b:
a+=1
if a>15:
break;#大于15跳出while循环 测试else语句可修改为a>20或者删掉
if a%2 != 0:
continue;#余数不等于0接着循环等于0打印操作
print(a, end=' ')
else:
print("a=%d"%(a))#只有break语句没执行才能走这块else(循环正常结束)
#while True:pass #pass为无占位语句,此写法为死循环且不做任何操作
D:\py\venv\Scripts\python.exe D:/py/test.py
python-learning hon-learning -learning arning ing
2 4 6 8 10 12 14
Process finished with exit code 0
for模式:
test=[1,2,3,4,5,"test",6]
for x in test:
if type(x) == str:
print("test")
break
if x%2 == 1:
print(x,end=" ")
else:
x=x+1
print(x,end=" ")
D:\py\venv\Scripts\python.exe D:/py/test.py
1 3 3 5 5 test
Process finished with exit code 0
其它用途:
py=open("test.txt","r")
while True:
line=py.readline()#整行读取
if not line:break
print(line,end=" ")
print("") #换行
py=open("test.txt","r")
while True:
line=py.read(50)#一次读取50字节
if not line:break
print(line,end=" ")
print("") #换行
for line in open("test.txt","r").readlines():#整行读取
print(line, end=" ")
print("") #换行
for line in open("test.txt","r"):#整行读取
print(line, end=" ")
print("") #换行
for line in open("test.txt","r").read(): #单字节读取
print(line, end=" ")
#计数器range产生这个数列表range(3):0,1,2;range(2,5):2,3,4;range(1,5,2):1,3
print("")#换行
L=list("test!")
for x in range(0,len(L),2):
print(L[x],end=" ")
D:\py\venv\Scripts\python.exe D:/py/test.py
python learning
123
python learning
123
python learning
123
python learning
123
p y t h o n l e a r n i n g
1 2 3
t s !
Process finished with exit code 0