python控制流

时间:2021-04-20 14:23:43

1. if...elif...else:

语法:

if 判断条件:

语句...

elif 判断条件:

语句...

else:

语句...

#elif语句可以有0个或多个

2. while和for循环:

while 判断条件:

语句...

for iterating_var in sequence:

statements(s)

可以在while循环体中嵌套for循环;也可以for循环中嵌套while循环。

3. for...else:for正常结束都会执行else

for...else:for正常结束(不执行break结束)都会执行else;若执行break,则不执行else

>>> for i in range(3):

...     print i

... else:

...     print "no break happens!"

...

0

1

2

no break happens!

>>> for i in range(5):

...     print i

...     break

... else:

...     print "no break happend"

...

0

4. while...else:while正常结束执行else

while...else:while正常结束(不执行break结束)都会执行else;若执行break,则不执行else

>>> n=2

>>> while n>1:

...     print n

...     n-=1

... else:

...     print "no break happend"

...

2

no break happend

>>> n=2

>>> while n>0:

...     print n

...     n-=1

...     break

... else:

...     print "no break happend"

...

2

(1) False:空、0、None、False

>>> bool([])

False

>>> bool(0)

False

>>> bool(None)

False

(2). True:1、True

>>> bool(1)

True

>>> bool(True)

True

>>> bool("s")

True

>>>

5. break、continue:

break:结束循环(彻底结束)

continue:结束本次循环,继续下一次循环

>>> for i in range(10):

...     if i % 2 ==0:

...         continue

...     print i

...

>>> for i in range(10):

...     if i%2==0:

...         break

...     print i

...

6. 遍历:

(1) 通过元素遍历

(2). 通过索引遍历

len():统计长度

>>> len("abc")

3

>>> len({1:2})  #统计字典长度

1

>>>

例1: for和while遍历字符串

>>> s="abcd"

>>> for i in range(len(s)):

...     print s[i]

...

>>> s

'abcd'

>>> i=0

>>> while i<len(s):

...     print s[i]

...     i+=1

...

例2: 遍历列表中的元组:

#coding=utf-8

a=[1,(12,3),(4,5),90]

for i in a:

if isinstance(i,(tuple,list)):

for j in i:

print j

else:

print i

7. for、while嵌套循环:

嵌套循环:在一个循环体里嵌入另一个循环

可以在while循环体中嵌套for循环;也可以for循环中嵌套while循环。

for iterating_var in sequence:

for iterating_var in sequence:

statements(s)

statements(s)

8. 直接退出多重循环:

(1). return退出多重循环:

#coding=utf-8

def test():

for i in range(5):

for j in range(5):

for k in range(5):

if i == j == k == 3:

return

else:

print i, '----', j, '----', k

test()

(2). 异常:

class getoutofloop(Exception):pass  #异常

try:

for i in range(5):

for j in range(5):

for k in range(5):

if i == j == k == 3:

raise getoutofloop()

else:

print i,'----',j,'----',k

except getoutofloop:

pass

print "done"

(3). break:(多个break)

#coding=utf-8

for i in range(5):

for j in range(5):

for k in range(5):

if i == j == k == 3:

break

else:

print i,'----',j,'----',k

else:continue

break

else:continue

break