python while循环
python 中最简单的循环机制是使用while
count=1
while count<5:
print(count)
count+=1
1
2
3
4
使用break跳出循环
如果我们想在无限循环的时候跳出循环,可以使用条件判断,一旦满足条件就跳出整个循环
c=1
while True:
c+=1
if c ==5:
break
print(c)
2
3
4
使用continue跳出当前的循环并进入下一个循环
有时候我们并不想结束整个循环,而是想在不满足某个条件的时候跳过去,比如输出奇数
x=1
while True:
if x >10:
break
x+=1
if x%2==0:
continue
print(x)
3
5
7
9
使用else
如果while循环正常结束(没有使用break跳出),程序将进入可选的else
s=[1,3,5,7]
x=0
while x<len(s):
n = s[x]
print(n)
if n%2==0:
break
x+=1
else:
print('hello this is else')
1
3
5
7
hello this is else