[Python3] loop control

Source: Internet
Author: User

Overview

In this section we mainly introduce the use of loop control in Python.

For loop

In Python, A for loop can traverse any sequence, such as tuples, lists, strings, dictionaries, collections, and so on.

First look at the general format of the FOR loop:

 for inch sequence:         # code block Else :             # code block    # Normally, we don't use else

    • Traversing tuples

Let's look at how the tuple traversal output is done with a for loop:

#-*-coding:utf-8-*-__author__= u'Gubei'if __name__=="__main__":    #For tuple traversalTuple_1 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)Print(U"iterate through the tuples and print them out:")     forTinchtuple_1:Print(t)

The results of the operation are as follows:

1234567890

    • Traverse List

Let's look at how to do a list traversal output with a For loop:

#-*-coding:utf-8-*-__author__= u'Gubei'if __name__=="__main__":        #For list TraversalList_1 = [u'Blog Park', u'Gubei', u'Python3']    Print(U"iterate through the list and print it out:")         forTextinchlist_1:Print(text)

The results of the operation are as follows:

Traverse the list and print it out: Blog Park Gubei Python3
    • Traverse Dictionary
      Let's look at two ways to traverse a dictionary:

#-*-coding:utf-8-*-__author__= u'Gubei 'if __name__=="__main__":    #For dictionary traversalDict_1 = {u"Blog Park": U"Cnblog"+ R"Gubei": U"Python3"}    Print(U"traverse the dictionary one way and print it out:")         for(Key, value)inchDict_1.items ():Print("%s:%s"%(key, value))Print("\ n-----------------------------")    Print(U"traverse the dictionary mode two and print it out:")     forKeyinchdict_1:Print("%s:%s"% (key, Dict_1[key]))

The results of the implementation are as follows:

-----------------------------
    • Use the range () function in conjunction with the range function to use this section.
      Range (start, end, step)
      Function Description: Generates a numeric sequence of a specified range in the specified step size
      Parameter description: Start: The starting value of a numeric sequence (default = 0) End: Number of values in a sequence step: spacing of values in a numeric sequence (default = 1)

Note: The sequence half-closed half-open interval generated by range

Let's look at an example as follows:

#-*-coding:utf-8-*-__author__= u'Gubei'if __name__=="__main__":    Print(U"range for loop instance")        #using default parameters to generate a sequence for traversal     forIinchRange (5):        Print(I, end=',')            #line Break    Print("')            #Specifies the range generation sequence to traverse     forIinchRange (0, 10):        Print(I, end=',')            #line Break    Print("')            #generating a sequence with a step-through method     forIinchRange (0, 10, 2):        Print(I, end=',')

The results of the implementation are as follows:

range for loop instance 0,1,2,3,4, 0,1,2,3,4,5,6,7,8,9, 0,2,4,6,8,
Nesting

Let's look at two for statements to implement a 99 multiplication table:

#-*-coding:utf-8-*-__author__= u'Gubei'if __name__=="__main__":    Print(U"99 multiplication Table:")         forIinchRange (1, 10):                 forJinchRange (I, 10):            Print(U"%d *%d =%2d"% (I, J, I * j), end="  ")        Print("")

The results of the implementation are as follows:

99 Multiplication Table:1 * 1 =  1  1 * 2 =  2  1 * 3 =  3  1 * 4 =  4  1 * 5 =  5  1 * 6 =  6
   1 * 7 =  7  1 * 8 =  8  1 * 9 =  9  2 * 2 =  4  2 * 3 =  6  2 * 4 =  8
   2 * 5 =  2 * 6 =  2 * 7 =  2 * 8 = 2  * 9 =  3 * 3 =  9  3 * 4 =  3 * 5 =  3 * 6 =  3 * 7 =  3 * 8 =  3 * 9 =  4 * 4 = 4  * 5 =  4 * 6 = 24
   4 * 7 =  4 * 8 =  4 * 9 = 5 * 5 = 5 * 6  = 5  * 7 =  5 * 8 = 5  * 9 =  6 * 6 =  6 * 7 =  6 * 8 =  6 * 9 =  7 * 7 = $  7 * 8 = 7  * 9 =  8 * 8 =  8 * 9 =  9 * 9 = 81  

While loop

Let's look at the general syntax for the while loop:

while 条件:    # 代码块

It is important to note that there is no do...while loop statement in Python.

Below we use the While loop statement to calculate all the even numbers of 0-100 and:

#-*-coding:utf-8-*-__author__= u'Gubei'if __name__=="__main__":    Print(U"calculates all 0-100 even and") n= 100Index=0 Sum=0 whileIndex <=N:sum= Sum +Index Index= index + 2Print(U"0-100 even and =%d"% sum)

The results are as follows:

Calculatesall even and 0 between 0-100
While and for synthesis use

Here we try to implement a 99 multiplication table with while and for combined:

#-*-coding:utf-8-*-__author__= u'Gubei'if __name__=="__main__":    Print(U"99 Multiplication Table instances:") n= 1 whileN <= 9:                 forMinchRange (N, 10):            Print(U"%d *%d =%2d"% (n, M, n*m), end="  ")        Print("") n= n + 1

The results of the operation are as follows:

99 Multiplication Table instance:1 * 1 =  1  1 * 2 =  2  1 * 3 =  3  1 * 4 =  4  1 * 5 =  5  1 * 6 =  6  1 * 7 =  7  1 * 8 =  8  1 * 9 =  9  2 * 2 =  4  2 * 3 =  6  2 * 4 =  8
   2 * 5 =  2 * 6 =  2 * 7 =  2 * 8 =  2 * 9 =  3 * 3 =  9  3 * 4 =  3 * 5 =  3 * 6 =  3 * 7 =  3 * 8 =  3 * 9 =  4 * 4 = 4 *  5 =  4 * 6 = 24
   4 * 7 =  4 * 8 =  4 * 9 = 5 * 5 = 5 * 6  = 5  * 7 =  5 * 8 = 5  * 9 =  6 * 6 =  6 * 7 =  6 * 8 = 6  * 9 =  7 * 7 = 7 *  8 = 7 * 9  =  8 * 8 =  8 * 9 =  9 * 9 = 81  

Break&continue
    • Break
      The break statement is used to control jumping out of a for or while loop body

    • Continue
      The continue statement is used to jump out of the remaining code statement in the current loop block and continue the next loop execution.

For the use of break and Continue statements This section does not do any sample demonstrations, please do your own research and practice.

[Python3] loop control

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.