While and for loops
General format
While <test>:
<statment>;
Else
<statment>;
The Else section is optional and is executed if control leaves the Wihle and there is no break.
Break: Jump out of the nearest loop
Continue: Jumps to the beginning of the nearest loop
Pass: Nothing is done, just a placeholder
else: It will only execute if it encounters a break
For loop
General format
For <target> in <object>:
<statment>
Else
<statment>
The For loop also supports an else part that also encounters a break to execute
Basic applications
For x in [' Spam ', ' eggs ', ' ham ']:
print (x);
sum = 0;
For x in [1,2,3,4]:
sum = sum+x;
print (sum);
Application of the For loop in tuples
T = [(UP), (3,4), (5,6)]
For (A, B) in T:
Print (A, b);
Dictionary
D = {' A ': 1, ' B ' =2, ' c ' = 3};
For key in D:
Print (key, ' = = ', D[key]);
Parallel traversal: Zip and map
The zip will take one or more sequences to make the parameters, then return a list of tuples, matching the side elements of those lists into pairs,
>>>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);
The built-in function map matches the sequence in a similar way, but if the parameters are different, the shorter none is used,
>>>S1 = ' abc ';
>>>s2 = ' xyz123 ';
>>>map (NONE,S1,S2);
[(' A ', ' X '), (' B ', ' Y '), (' C ', ' Z '), (None, ' 1 '), (None, ' 2 '), (None, ' 3 ')]
Python learning while and for loops