Python basic article "fourth": Looping statements

Source: Internet
Author: User

The Loop statement contains: while and for statements

While loop

Whil-Loop expression:

 while Judging Condition: (Here a unified four spaces) statement

Be sure to note the colon after indentation and judging conditions!

For example, use while to calculate the 1-100 and:

1 # !/usr/bin/env Python3 2 3 A = 4   b = 0  5 counter = 1 6 7 while counter <=
   
     A: 
     8     B = b +
     counter 
     9     counter + 1
    
    print(b )
   

Result of Operation:

1 /library/frameworks/python.framework/versions/3.5/bin/python3.5/users/zk/pycharmprojects/old_boy/ day02/Loop/while. PY2 505034 Process finished with exit code 0

For statement

A For loop can traverse any sequence of items, such as a list or a string.

For loop format:

1  for  in < sequence >:2     < disclaimer >3else:4     < Statement >

Jump out of break in the loop:

1 #!/usr/bin/env Python32 3A = ["C","C + +","Perl","Python"]4  forIinchA:5      ifi = ='C':6          Print('the list contains C')7           Break   #jump out of this cycle8      Print('nice work.')9 Else:Ten      Print('there is no C in the list') One Print('hehe')

Operation Result:

1 /library/frameworks/python.framework/versions/3.5/bin/python3.5/users/zk/pycharmprojects/old_boy/ day02/Loop/while. PY2 list contains C3 hehe 45 Process finished with exit code 0

Range () function

If you need to traverse a list of numbers, you can use the built-in function range (). He will generate a series:

1  for  in range (5):2 ...  Print (i) 3  405 16 27 38 4

You can also specify values for range ranges:

1  for  in range (5,9):2  ... Print . IO 3  4 55 66 77 8

You can also use range to specify a number to start with and specify a different increment (even negative; sometimes called a step).

1  for  in range (0,10,3):2  ... Print (i) 3  405 36 67 9

You can also traverse the index of a sequence by combining the range () and Len () functions:

1>>> a = ['Mary','had','a','Little','Lamb']2>>> forIinchRange (len (a)):3...Print(i,a[1])4 ... 5 0 had61had72had83had94hadTen>>> forIinchRange (len (a)): One...Print(I,a[i]) A ...  - 0 Mary -1had the2a -3Little -4 Lamb

Create a list with the range () function:

1 >>> list (range (5))2 [0, 1, 2, 3, 4]

Brea and continue statements and else sub-statements in loops

The break statement can jump out of a for and while loop body. If you terminate from a for or while loop, any corresponding loop else blocks will not execute.

The continue statement is used to tell Python to skip the remaining statements in the current loop block and proceed to the next round of loops.

A looping statement can have an ELSE clause, which is executed when the exhaustion list (in a For loop) or the condition becomes false (in a while loop), but not when the loop is terminated by a break. The following is an example of a loop that searches for prime numbers:

1  forIinchRange (2,10):2      forXinchRange (2, i):3         ifI% x = =0:4             PrintI'equals'X'*', i//x)5              Break6 Else:7      PrintI'Is a prime number')

Operation Result:

1 /library/frameworks/python.framework/versions/3.5/bin/python3.5/users/zk/pycharmprojects/old_boy/  day02/Loop/while. PY2 4 equals 2 * 23 6 equals 2 * 34 8 equals 2 * 45 9 Equals 3 * 36 is a primenumber78 Process finished with exit code 0

Pass Statement

The pass statement does nothing. It only requires a statement in syntax but is used when the program does not require any action. For example:

1  while True: 2 ...     Pass # If the carriage return is still waiting for the status 3  

Enumrate

To add an ordinal to an object that is iterative:

1 li = ['haha','hehe','asd' , 124]2 for in Enumerate (li,1):     #1 means to add an ordinal from the beginning  3     print(k,v)

Operation Result:

1 /library/frameworks/python.framework/versions/3.5/bin/python3.5/users/zk/pycharmprojects/old_boy/ day02/Loop/While. py2 1 haha3 2 hehe4 3 ASD  5 4 12467 Process finished with exit code 0

* Xrange is gone in python3.x, range is equivalent to xrange in python2.x

Python basic article "fourth": Looping statements

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.