Python013 Python3 loop statement, python013python3

Source: Internet
Author: User

Python013 Python3 loop statement, python013python3

Python3 loop statement
This section describes how to use Python loop statements.
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 calculate the sum of 1 to 100:
Instance

#! /Usr/bin/env python3 n = 100 sum = 0 counter = 1 while counter <= n: sum = sum + counter + = 1 print ("1 to % d: % d" % (n, sum ))


The execution result is as follows:

Sum from 1 to 100: 5050

Infinite Loop

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

#! /Usr/bin/python3 var = 1 while var = 1: # The expression is always true num = int (input ("enter a number :")) print ("the number you entered is:", num) print ("Good bye! ")

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

Enter a number: 5 the number you entered is: 5 enter a number:

You can use CTRL + C to 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:
Instance

#! /Usr/bin/python3 count = 0 while count <5: print (count, "Less than 5") count = count + 1 else: print (count, "greater than or equal to 5 ")

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

0 less than 51 less than 52 less than 53 less than 54 less than 55 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:
Instance

#!/usr/bin/python flag = 1 while (flag): print ('QQ603374730!') print ("Good bye!")

Note:You can use CTRL + C to interrupt the above infinite loop.
Run the preceding script and the output result is as follows:

QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!QQ603374730!Process finished with exit code 1

  

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:
Instance

>>>languages = ["C", "C++", "Perl", "Python"] >>> for x in languages:...     print (x)... CC++PerlPython>>>

The following for instance uses the break statement, which is used to jump out of the current loop body:
Instance

#! /Usr/bin/python3 sites = ["Baidu", "Google", "Runoob", "Taobao"] for site in sites: if site = "Runoob ": print ("QQ603374730! ") Break print (" cyclic data "+ site) else: print (" No cyclic data! ") Print (" finished loop! ")

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

Cyclic data Baidu cyclic data GoogleQQ603374730! Complete cycle!

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

>>>for i in range(5):...     print(i)...01234

You can also use range to specify the range value:
Instance

>>>for i in range(5,9) :    print(i)     5678>>>

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

>>>for i in range(0, 10, 3) :    print(i)     0369>>>

Negative Number:
Instance

>>>for i in range(-10, -100, -30) :    print(i)     -10-40-70>>>

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

>>>a = ['Google', 'Baidu', 'QQ603374730', 'Taobao', 'QQ']>>> for i in range(len(a)):...     print(i, a[i])... 0 Google1 Baidu2 QQ6033747303 Taobao4 QQ>>>

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

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

Break and continue statements and else clauses in the loop
The break statement 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:
Instance

#! /Usr/bin/python3 for letter in 'runoob': # first instance if letter = 'B': break print ('current letter: ', letter) var = 10 # The Second Instance while var> 0: print ('current variable value: ', var) var = var-1 if var = 5: break print ("Good bye! ")

The output result of executing the above script is:

Current letter: R current letter: u current letter: n current letter: o current variable value: 10 current variable value: 9 current variable value: 8 current variable value: 7 current variable value: 6 Good bye!

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

Instance

#! /Usr/bin/python3 for letter in 'runoob': # first instance if letter = 'O': # When the letter is o, skip output continue print ('current letter: ', letter) var = 10 # The Second Instance while var> 0: var = var-1 if var = 5: # When the variable is 5, the output continue print ('current variable value: ', var) print ("Good bye! ")

The output result of executing the above script is:

Current letter: R current letter: u current letter: n current letter: B Current variable value: 9 current variable value: 8 current variable value: 7 current variable value: 6 current variable value: 4. Current variable value: 3. Current variable value: 2. Current variable value: 1. Current variable value: 0 Good bye!

A loop statement can have an else clause, which is executed when the list (for loop) is exhausted or the condition changes to false (for loop while LOOP), resulting in loop termination, however, the loop is terminated by the break and is not executed.
The following example shows a cycle for querying prime numbers:
Instance

#! /Usr/bin/python3 for n in range (2, 10): for x in range (2, n): if n % x = 0: print (n, 'equals ', x,' * ', n // x) break else: # The print element is not found in the loop (n,' is a prime number ')

The output result of executing the above script is:

2 is prime number 3 is prime number 4 equals 2*25 is prime number 6 equals 2*37 is prime number 8 equals 2*49 equals 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.
Instance

>>> While True:... pass # Wait for the keyboard to be interrupted (Ctrl + C)

 

Minimum class:
Instance

>>>class MyEmptyClass:...     pass

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

Instance

#! /Usr/bin/python3 for letter in 'runoob': if letter = 'O': pass print ('execute pass Block') print ('current letter: ', letter) print ("Good bye! ")

The output result of executing the above script is:

Current letter: R current letter: u current letter: n execution pass block current letter: o current letter: bGood bye!

Python3 condition Control

Use the built-in enumerate function for traversal:

for index, item in enumerate(sequence):    process(index, item)

Instance

>>> sequence = [12, 34, 34, 23, 45, 76, 89]>>> for i, j in enumerate(sequence):...     print(i, j)... 0 121 342 343 234 455 766 89

For Loop 1-100 sum of all Integers

#! /Usr/bin/env python3n = 0sum = 0for n in range (0,101): # n range 0-100 sum + = nprint (sum)

Use loop nesting to implement 99 multiplication rules:

#! /Usr/bin/python3 # number of rows under cyclic control at the external layer # I is the number of rows I = 1 while I <= 9: # cyclically control the number of columns in each row j = 1 while j <= I: mut = j * I print ("% d * % d = % d" % (j, i, mut), end = "") j + = 1 print ("") I + = 1

Examples of nested for loops:

#!/usr/bin/python3for i in range(1,6):   for j in range(1, i+1):      print("*",end='')   print('\r')

Output result:

***************

 

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.