Python中的循环以及break/continue/else/pass

来源:互联网 发布:java泛型方法 编辑:程序博客网 时间:2024/05/17 23:17

转:http://blog.csdn.net/u010278162/article/details/52102574

While和For循环。

1、while。

结构:

while 条件:

    opts

else:

    opts

一个简单的小例子:

[python] view plain copy
  1. i = 0  
  2. while i < 10 :  
  3.     print i   
  4.     i = i + 1   
结果:0 1 2 3 4 5 6 7 8 9

带有else的小例子:

[python] view plain copy
  1. i = 0  
  2. while i < 10 :  
  3.     print i   
  4.     i = i + 1   
  5. else:  
  6.     print 'It is over.'  
  7.   
  8. i = 0  
  9. while i < 10 :  
  10.     print i   
  11.     i = i + 1   
  12.     if i == 7:  
  13.         break;  
  14. else:  
  15.     print 'It is over.'  

结果:


如果while正常执行完,则会执行else中的内容,如果遇到break跳出循环,则else中的内容也不会执行。

2、break、continue、pass介绍

break:跳出当前循环

continue:跳出本次循环,进行下一次循环

pass:什么也不做,占位。

一个例子显而易见:

[python] view plain copy
  1. i = 0  
  2. while i < 10 :  
  3.       
  4.     i = i + 1   
  5.     if i == 4:  
  6.         pass  
  7.     if i == 6:  
  8.         continue  
  9.     if i == 8:  
  10.         break  
  11.     print i   
  12. else:  
  13.     print 'It is over.'  

结果:1 2 3 4 5 7 跳过了6,进入7的循环,到8时跳出了循环。


3、for循环。

结构:

for 变量* in 迭代器:

    opts

else:

    opts

变量可以是一个,也可以是多个,看例子:

[python] view plain copy
  1. _list = [1,2,3,4,5]  
  2. _tuple = ((1,2),(3,4),(6,5),(7,7))  
  3. _dict = {'1':1,'2':2,'3':3}  
  4.   
  5. for i in _list:  
  6.     print i  
  7.   
  8. for i in _tuple:  
  9.     print i   
  10.   
  11. for x,y in _tuple:  
  12.     print x,y  
  13. print [x for x,y in _tuple if x>y]  
  14. #for x,y in _tuple if x>y:  
  15.     #print x   #报错,不能这样写  
  16.   
  17. for i in _dict:  
  18.     print i  
  19.   
  20. for i in _dict:  
  21.     print i,'the value is+',_dict[i]  
  22.   
  23. for key,value in _dict.items():#items()方法返回字典的(键,值)元组对的列表  
  24.     print key,'the value is_',value  
  25.   
  26. #for i in _dict:  
  27.     #print i.(''+i) #baocuo   
结果:

原创粉丝点击