Home  >  Article  >  Backend Development  >  Nesting of Python loop statements, which has become popular in recent years, is explained with examples (take break as an example)

Nesting of Python loop statements, which has become popular in recent years, is explained with examples (take break as an example)

Tomorin
TomorinOriginal
2018-08-13 15:55:203169browse

Python language is a very loose language. The Python language allows you to embed another loop inside a loop body. This is called Nested loop.

The following figure is the nested loop structure:

Nesting of Python loop statements, which has become popular in recent years, is explained with examples (take break as an example)

Python for loop nested syntax:

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

Python while loop nesting syntax:

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

You can embed other loop bodies in the loop body. For example, you can embed a for loop in a while loop. On the contrary, you can embed other loop bodies in a for loop. Embed a while loop in it.

The following example uses a nested loop to output a prime number between 2 and 100:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 i = 2while(i < 100):
  j = 2
   while(j <= (i/j)):
       if not(i%j): break
      j = j + 1
   if (j > i/j) : print i, " 是素数"
   i = i + 1
 print "Good bye!"

The above example output result:

2 is a prime number
3 is a prime number
5 is a prime number
7 is a prime number
11 is a prime number
13 is a prime number
17 is a prime number
19 is a prime number
23 is a prime number
29 is a prime number
31 is a prime number
37 is a prime number
41 is a 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!

Control loop statements related to this article:

Usage and function of the continue statement of Python statement

Python The break statement in the statement jumps out of the loop instance

What is the function of the pass statement in the Python statement? A brief discussion on the usage of pass statement


The above is the detailed content of Nesting of Python loop statements, which has become popular in recent years, is explained with examples (take break as an example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn