Python loop statements

Source: Internet
Author: User

Python loop statements
Python While LOOP statement

In Python programming, the while statement is used to execute a program cyclically. That is, under a certain condition, a program is executed cyclically to process the same task that needs to be processed repeatedly. The basic form is:

While judgment condition: execution statement ......

The execution statement can be a single statement or statement block. The condition can be any expression, and any non-zero or non-null value is true.

When the condition is false, the loop ends.

The execution flow chart is as follows:

Instance:

#!/usr/bin/pythoncount = 0while (count < 9):   print 'The count is:', count   count = count + 1print "Good bye!"

The output result of the above code execution:

The count is: 0The count is: 1The count is: 2The count is: 3The count is: 4The count is: 5The count is: 6The count is: 7The count is: 8Good bye!

When the while statement is run, there are two other important commands: continue, break to skip the loop. continue is used to skip this loop, and break is used to exit the loop, in addition, the "judgment condition" can also be a constant value, indicating that the cycle must be true. The specific usage is as follows:

# Continue and break usage I = 1 while I <10: I + = 1 if I % 2> 0: # Skip output continue print I # output dual number 2, 4, 6, 8, 10i = 1 while 1: # print I # output 1 ~ must be set when the loop condition is 1 ~ 10 I + = 1 if I> 10: # break out of the loop when I is greater than 10

Infinite Loop

If the condition determination statement is always true, the loop will be executed infinitely, as shown in the following example:

#! /Usr/bin/python #-*-coding: UTF-8-*-var = 1 while var = 1: # This condition is always true, the loop will be infinitely executed num = raw_input ("Enter a number:") print "You entered:", numprint "Good bye! "

 

Output result of the above instance:

Enter a number  :20You entered:  20Enter a number  :29You entered:  29Enter a number  :3You entered:  3Enter a number between :Traceback (most recent call last):  File "test.py", line 5, in 
 
      num = raw_input("Enter a number :")KeyboardInterrupt
 

 

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


Loop using else statements

In python,... Else indicates this. The statements in for are no different from those in general. The statements in else are executed after the loop is executed normally (that is, the for statements are not interrupted by the break jump, while... The same is true for else.

#!/usr/bin/pythoncount = 0while count < 5:   print count, " is  less than 5"   count = count + 1else:   print count, " is not less than 5"

The output result of the above instance is:

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

#!/usr/bin/pythonflag = 1while (flag): print 'Given flag is really true!'print "Good bye!"

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

 

 

Python for loop statements

 

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

Syntax:

The syntax format of the for Loop is as follows:

for iterating_var in sequence:   statements(s)

Flowchart:

Vcl9sb29w "class =" alignnone size-full wp-image-4022 "height =" 351 "src =" http://www.bkjia.com/uploads/allimg/151209/0430041204-1.jpg "width =" 388 "/>

Instance:

#! /Usr/bin/python #-*-coding: UTF-8-*-for letter in 'python': # First Instance print 'current letter :', letterfruits = ['bana', 'apple', 'mango'] for fruit in fruits: # print the second instance 'current letter: ', fruitprint "Good bye! "

Try it?

Output result of the above instance:

Current letter: P current letter: y current letter: t current letter: h current letter: o current letter: n current letter: banana current letter: apple current letter: mangoGood bye!

Iterative by sequential Index

Another way to traverse the execution cycle is by indexing, as shown in the following example:

#! /Usr/bin/python #-*-coding: UTF-8-*-fruits = ['bana', 'apple ', 'mango'] for index in range (len (fruits): print 'current fruit: ', fruits [index] print "Good bye! "

Output result of the above instance:

Current fruit: banana current fruit: apple current fruit: mangoGood bye!

In the above example, we use the built-in functions len () and range (). The function len () returns the length of the list, that is, the number of elements. Range returns the number of sequences.


Loop using else statements

In python,... Else indicates this. The statements in for are no different from those in general. The statements in else are executed after the loop is executed normally (that is, the for statements are not interrupted by the break jump, while... The same is true for else.

Example:

#! /Usr/bin/python #-*-coding: UTF-8-*-for num in range (): # iterations of numbers between 10 and 20 for I in range (2, num): # iteration Based on the factor if num % I = 0: # determine the first factor j = num/I # Calculate the second factor print '% d equals % d * % d' % (num, I, j) break # Jump out of the current loop else: # print num of the loop else, 'is a prime number'

Output result of the above instance:

10 equals 2*511 is a prime number 12 equals 2*613 is a prime number 14 equals 2*715 equals 3*516 equals 2*817 is a prime number 18 equals 2*919 is a prime number
Python loop nesting

The Python language allows you to embed another loop in a loop body.

Python for nested loop Syntax:

for iterating_var in sequence:   for iterating_var in sequence:      statements(s)   statements(s)

Python while LOOP nested Syntax:

while expression:   while expression:      statement(s)   statement(s)

You can embed other loop bodies in a loop. for example, you can embed a for Loop in a while loop. Otherwise, you can embed a while loop in a for loop.

Instance:

The following example uses nested loop output 2 ~ Prime number between 100:

#! /Usr/bin/python #-*-coding: UTF-8-*-I = 2 while (I <100): j = 2 while (j <= (I/j )): if not (I % j): break j = j + 1 if (j> I/j): print I, "is a prime number" I = I + 1 print "Good bye! "

Output result of the above instance:

2 is prime number 3 is prime number 5 is prime number 7 is Prime Number 11 is prime number 13 is prime number 17 is prime number 19 is prime number 23 is prime number 29 is prime number 31 is prime number 37 is prime number 41 is prime number 43 is a prime number 47 is a prime number 53 is a prime number 59 is a prime number 61 is a prime number 67 is a prime number 71 is a prime number 73 is a prime number 79 is a prime number 83 is a prime number 89 is a prime number 97 is a prime number Good bye!

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.