Home  >  Article  >  Backend Development  >  What is python loop nesting? (code example)

What is python loop nesting? (code example)

乌拉乌拉~
乌拉乌拉~Original
2018-08-14 11:48:073008browse

I believe everyone has just come into contact with the python language. Today, this article will help you understand the knowledge point of python loop nesting. Specifically, I will introduce two loop methods to you, namely for loop and while loop. The Python language allows embedding another loop inside a loop body. In this article, I will explain some pythonloop nesting examples to help you understand. I hope this article can bring you some help and help you avoid detours when learning python.

1. Python for loop nesting syntax:

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

2. Python while loop nesting syntax:

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

You can embed other loop bodies within the loop body. For example, you can embed a for loop within a while loop. Conversely, you can embed a while loop within a for loop.

Only description and structure may have no practical effect. Next, I will give an example to deepen the understanding of this knowledge point:

#!/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, " 是素数"
   i = i + 1
 
print "Good bye!"

The output results of the above example are as follows Display:

2 是素数
3 是素数
5 是素数
7 是素数
11 是素数
13 是素数
17 是素数
19 是素数
23 是素数
29 是素数
31 是素数
37 是素数
41 是素数
43 是素数
47 是素数
53 是素数
59 是素数
61 是素数
67 是素数
71 是素数
73 是素数
79 是素数
83 是素数
89 是素数
97 是素数
Good bye!

This article explains the knowledge points of Python loop nesting and demonstrates some examples of it. Nested loops are a very practical thing to learn, and you'll find yourself using them in many situations. I hope this article can bring some help to you who are learning python

For more related knowledge, please visit the Python tutorial column of the php Chinese website.

The above is the detailed content of What is python loop nesting? (code 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