Python3 loop statement (10) and python3 loop statement

Source: Internet
Author: User

Python3 loop statement (10) and python3 loop statement

The loop statements in Python include for and while.

The control structure of the Python loop statement is as follows:

While Loop

The general form of the while statement in Python:

While judgment condition: Statement

Pay attention to the colon and indentation. In addition, there is no do... while loop in Python.

The following example uses while to output all the even numbers between 1 and 10:

1 num = 102 count = 03 while num> 0: 4 if num % 2 = 0: 5 print (num) 6 count + = 17 num-= 18 print ("One has", count, "even! ")

The execution result is as follows:

1 102 83 64 45 26 one has five even numbers!

Example 9-9 multiplication table:

1 a=12 while a<10 :3     b=14     while b<=a :5         print(str(b)+"x"+str(a)+"="+str(a*b),end="\t")6         b +=17     print()8     a +=1

Execution result:

1 1x1=1    2 1x2=2    2x2=4    3 1x3=3    2x3=6    3x3=9    4 1x4=4    2x4=8    3x4=12    4x4=16    5 1x5=5    2x5=10    3x5=15    4x5=20    5x5=25    6 1x6=6    2x6=12    3x6=18    4x6=24    5x6=30    6x6=36    7 1x7=7    2x7=14    3x7=21    4x7=28    5x7=35    6x7=42    7x7=49    8 1x8=8    2x8=16    3x8=24    4x8=32    5x8=40    6x8=48    7x8=56    8x8=64    9 1x9=9    2x9=18    3x9=27    4x9=36    5x9=45    6x9=54    7x9=63    8x9=72    9x9=81    

 

Infinite Loop

We can set the conditional expression to never be false to implement an infinite loop. The example is as follows:

1 #! /Usr/bin/python32 3 var = 14 while var = 1: # The expression is always true5 num = int (input ("enter a number :")) 6 print ("the number you entered is:", num) 7 8 print ("Good bye! ")

Run the preceding script and the output result is as follows:

1 enter a number: 52 the number you entered is: 53 enter a number:

You can useCTRL + CTo exit the current infinite loop.

Infinite loops are very useful for client real-time requests on the server.

While loop use else statement

In the while... When the condition is false, else executes the statement block of else:

1 #! /Usr/bin/python32 3 count = 04 while count <5:5 print (count, "Less than 5") 6 count = count + 17 else: 8 print (count, "greater than or equal to 5 ")

Run the preceding script and the output result is as follows:

1 0 less than 52 1 less than 53 2 less than 54 3 less than 55 4 less than 56 5 greater than or equal to 5
Simple statement Group

Similar to the if statement syntax, if your while LOOP body contains only one statement, you can write the statement and while statement in the same line, as shown below:

1 #! /Usr/bin/python2 3 flag = 14 5 while (flag): print ('Welcome! ') 6 7 print ("Good bye! ")

Note:You can use CTRL + C to interrupt the above infinite loop.

For statement

A Python for loop can traverse any series of projects, such as a list or a string.

The general format of the for Loop is as follows:

for <variable> in <sequence>:    <statements>else:    <statements>

Python loop instance:

1 >>>languages = ["C", "C++", "Perl", "Python"] 2 >>> for x in languages:3 ...     print (x)4 ... 5 C6 C++7 Perl8 Python9 >>>

The following for instance is usedBreakStatement. The break statement is used to jump out of the current loop body:

1 #! /Usr/bin/python3 2 3 sites = ["Baidu", "Google", "Runoob", "Taobao"] 4 for site in sites: 5 if site = "Runoob": 6 print ("hello Python! ") 7 break 8 print (" cyclic data "+ site) 9 else: 10 print (" No cyclic data! ") 11 print (" finished loop! ")

After the script is executed, the loop body jumps out when the loop reaches "Runoob:

1. Loop Data Baidu2 Loop Data Google3 hello Python! 4. Complete the loop!
Range () function

If you need to traverse numeric sequences, you can use the built-in range () function. It generates a series, for example:

1 >>>for i in range(5):2 ...     print(i)3 ...4 05 16 27 38 4

You can also use range to specify the range value:

1 >>>for i in range(5,9) :2     print(i)3  4     5 56 67 78 89 >>>

You can also set range to start with a specified number and specify different increments (or even negative numbers, sometimes called 'step '):

1 >>>for i in range(0, 10, 3) :2     print(i)3  4     5 06 37 68 99 >>>

You can combine the range () and len () functions to traverse the index of a sequence, as shown below:

 1 >>>a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ'] 2 >>> for i in range(len(a)): 3 ...     print(i, a[i]) 4 ...  5 0 Google 6 1 Baidu 7 2 Runoob 8 3 Taobao 9 4 QQ10 >>>

You can also use the range () function to create a list:

1 >>>list(range(5))2 [0, 1, 2, 3, 4]3 >>>
Break and continue statements and else clauses in the loop

BreakStatement can jump out of the for and while LOOP bodies. If you terminate a for or while LOOP, no corresponding loop else block will be executed. Example:

1 #! /Usr/bin/python3 2 3 for letter in 'runoob': # First Instance 4 if letter = 'B': 5 break 6 print ('current letter :', letter) 7 8 var = 10 # The Second Instance 9 while var> 0: 10 print ('current variable value: ', var) 11 var = var-112 if var = break14 15 print ("Good bye! ")

The output result of executing the above script is:

1 current letter: R 2 current letter: u 3 current letter: n 4 current letter: o 5 current letter: o 6 current variable value: 10 7 current variable value is: 9 8 current variable value is: 8 9 current variable value is: 710 current variable value: 611 Good bye!

ContinueThe statement is used to tell Python to skip the remaining statements in the current loop block and continue the next loop.

1 #! /Usr/bin/python3 2 3 for letter in 'runoob': # First Instance 4 if letter = 'O ': # When the letter is o, skip output 5 continue 6 print ('current letter: ', letter) 7 8 var = 10 # The Second Instance 9 while var> 0: 10 var = var-111 if var = 5: # When the variable is 5, skip OUTPUT 12 continue13 print ('current variable value: ', var) 14 print ("Good bye! ")

The output result of executing the above script is:

1 current letter: R 2 current letter: u 3 current letter: n 4 current letter: B 5 current variable value: 9 6 current variable value: 8 7 current variable value: 7 8 current variable value: 6 9 current variable value: 410 current variable value: 311 current variable value: 212 current variable value: 113 current variable value: 014 Good bye!

Loop statements can haveElseClause, which is executed when the endless list (with for loop) or condition changes to false (with while LOOP), but is not executed when the loop is terminated by break.

The following example shows a cycle for querying prime numbers:

1 #! /Usr/bin/python3 2 3 for n in range (2, 10): 4 for x in range (2, n): 5 if n % x = 0: 6 print (n, 'equals ', x,' * ', n // x) 7 break 8 else: 9 # element 10 print (n, 'is a prime number ')

The output result of executing the above script is:

1 2 is prime number 2 3 is prime number 3 4 is equal to 2*24 5 is prime number 5 6 is equal to 2*36 7 is prime number 7 8 is equal to 2*48 9 is equal to 3*3
Pass statement

Python pass is a null statement to maintain the integrity of the program structure.

Pass does not do anything. It is generally used as a placeholder statement, as shown in the following example:

1 >>> while True: 2... pass # Wait for the keyboard to interrupt (Ctrl + C)

Minimum class:

1 >>>class MyEmptyClass:2 ...     pass

The following example executes the pass statement block when the letter is o:

1 #! /Usr/bin/python32 3 for letter in 'runoob': 4 if letter = 'O': 5 pass6 print ('execution pass Block') 7 print ('current letter: ', letter) 8 9 print ("Good bye! ")

The output result of executing the above script is:

1 current letter: R2 current letter: u3 current letter: n4 execute pass block 5 current letter: o6 execute pass block 7 current letter: o8 current letter: b9 Good bye!

 

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.