Examples: How to Use nested loop statements in Python

Source: Internet
Author: User
This article describes how to use nested loop statements in Python as an example. It is the basic knowledge in getting started with Python. If you need it, you can refer to the Python programming language to allow nesting of another loop in one loop. The following describes several examples to illustrate this concept.
Syntax

The syntax of nested loop statements in Python is as follows:

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

The Python programming language allows nesting of another loop in one loop. The following describes several examples to illustrate this concept.
Syntax

The syntax of nested loop statements in Python is as follows:

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

The syntax of a nested while LOOP statement in the Python programming language is as follows:

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

At the end of loop nesting, it should be noted that any type of loop can be included in any other type of loop. For example, a while loop can be placed in a for loop, and vice versa.
Example

The following program uses a nested loop to find all prime numbers from 2 to 100:

#!/usr/bin/pythoni = 2while(i < 100):  j = 2  while(j <= (i/j)):   if not(i%j): break   j = j + 1  if (j > i/j) : print i, " is prime"  i = i + 1print "Good bye!"

When the above code is executed, it will produce the following results:

2 is prime3 is prime5 is prime7 is prime11 is prime13 is prime17 is prime19 is prime23 is prime29 is prime31 is prime37 is prime41 is prime43 is prime47 is prime53 is prime59 is prime61 is prime67 is prime71 is prime73 is prime79 is prime83 is prime89 is prime97 is primeGood 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.