Condition and loop

Source: Internet
Author: User
Tags switch case

Condition and loop
1. if statement

 

 1 >>>a=7 2 >>> if a<0: 3 ...     print 'Negative changed to zero' 4 ... elif a==0: 5 ...     print 'Zero' 6 ... elif a==1: 7 ...     print 'Single' 8 ... else: 9 ...     print 'More'10 ...     11 More

 

Elif is short for 'else if'. The use of the if statement implements switch case statement usage.

2. for statement

 

1 >>> words = ['cat','fish','window']2 >>> for w in words[:]:3 ...     if len(w)>5:4 ...         words.insert(0,w)5 ...         6 >>> words7 ['window', 'cat', 'fish', 'window']

 

Note: words [:]. If it is words, it becomes an endless loop. If you modify the list in the traversal list loop, we recommend that you copy the list first.

 

 

3. range () function

 

This function is used to create a new table. The elements in this table are all integers. Starting from 0, the next element is 1 larger than the previous one until the upper limit written in the function (excluding the upper limit itself ).

 1 >>> range(10) 2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 3 >>> range(0,10,3) 4 [0, 3, 6, 9] 5  6 >>> a=['Mary','had','a','little','lamb'] 7 >>> for i in range(len(a)): 8 ...     print i,a[i] 9 ...     10 0 Mary11 1 had12 2 a13 3 little14 4 lamb
4. break and continue statements

 

Continue # If a continue is encountered during a loop execution, skip this execution and perform the next operation.

 

Break # Stop the entire execution cycle

1 >>> for i in range(5):2 ...     if i==2:3 ...         continue4 ...     print i5 ...     6 07 18 39 4

When the loop is executed to I = 2, The if condition is true, and the continue is triggered. Skip this execution (do not execute print) and continue the next execution (I = 3 ).

>>> for i in range(5):...     if i==2:...         break...     print i...     01

When the loop is executed to I = 2, The if condition is true, the break is triggered, and the entire loop is stopped.

5. Summary

Range ()

For element in sequence:

While condition:

Continue

Break

 

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.