Python learning while and for loops

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.