Python:循环语句

时间:2020-12-11 08:32:51

while

在某种条件下,执行某段程序

>>> w=0
>>> while w<5:
... print 'w :',w
... w=w+1
...
w : 0
w : 1
w : 2
w : 3
w : 4

continue

跳过位于之后的语句,开始下一轮循环

#输出10以内偶数
>>> c=1
>>> while c<10:
... c+=1
... if c%2>0:
... continue
... print c
...
2
4
6
8
10

break

跳出循环

>>> b=1
>>> while 1:
... print b
... b+=1
... if b>5:
... break
...
1
2
3
4
5

while..else

>>> e=1
>>> while e<5:
... print e,'<5'
... e+=1
... else:
... print e,'=5'
...
1 <5
2 <5
3 <5
4 <5
5 =5

for

可以遍历整个序列

>>> for f in 'hello':
... print f
...
h
e
l
l
o

索引

>>> singer=['adele','taylor','lana']
>>> for index in range(len(singer)):
... print 'singer:',singer[index]
...
singer: adele
singer: taylor
singer: lana

for..else

>>> for num in range(10,20):
... for i in range(2,num):
... if num%i==0:
... j=num/i
... print '%d=%d*%d'%(num,i,j)
... break
... else:
... print num,'is a prime number'
...
10=2*5
11 is a prime number
12=2*6
13 is a prime number
14=2*7
15=3*5
16=2*8
17 is a prime number
18=2*9
19 is a prime number

嵌套

#输出100以内所有素数

#!/usr/bin/python
# -*- coding: UTF-8 -*-
i = 2
while(i < 100):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print i, "is a prime number"
i = i + 1

  嵌套等价语句

#!/usr/bin/python
# -*- coding: UTF-8 -*-
for num in range(2,101):
for i in range(2,num):
if num%i==0:
j=num/i
break
else:
print num,'is a prime number'
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import math
for i in range(50, 100 + 1):
for j in range(2, int(math.sqrt(i)) + 1): #比 i的开平方小的最大整数
if i % j == 0:
break
else:
print i,'is a prime number'

暂时这些,后续补充..