python学习之while 和for循环

while 和for循环

一般格式
while <test>:
  <statment>;
else:
  <statment>;


else 部分为可选部分,(控制权离开wihle而有没有碰到break的情况下会执行)

break :跳出最近所在的循环
continue :跳到最近所在的循环的开头处
pass :什么事情也不做,只是一个占位符
else :碰到break才会执行


for循环
一般格式
for <target> in <object>:
  <statment>
else:
  <statment>


for循环也支持一个else部分 同样是碰到break才会执行


基本应用

for x in ['spam','eggs','ham']:
  print(x);


sum = 0;
for x in [1,2,3,4]:
  sum = sum+x;
print(sum);


for循环在元组中的应用
T = [(1,2),(3,4),(5,6)]

for (a,b) in T:
  print(a,b);


字典
D = {'a':1,'b'=2,'c'=3};
for key in D:
  print(key,'=>',D[key]);


并行遍历:zip和map
zip会取得一个或者多个序列做参数,然后返回元组的列表,将这些列表的并排元素配成对,
>>>L1 = [1,2,3,4];
>>>L2 = [5,6,7,8];

>>>zip(L1,L2);
>>>list(zip(L1,L2));
[(1,5),(2,6),(3,7),(4,8)]

>>>for (x,y) in zip(L1,L2):
  print(x,y,'--',x+y);

内置函数map用类似的方法把序列配对起来,但是如果参数不同,会用较短的none补齐,

>>>s1 = 'abc';
>>>s2 = 'xyz123';

>>>map(none,s1,s2);
[('a','x'),('b','y'),('c','z'),(none,'1'),(none,'2'),(none,'3')]

原文地址:https://www.cnblogs.com/techdreaming/p/5184364.html