python循环语句

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

 

 

 

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值