Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python3 loop


May 10, 2021 Python3


Table of contents


This section will cover the use of Python loop statements.

Loop statements in Python have for and while.

The control structure diagram of the Python loop statement looks like this:

Python3 loop


While loop

The general form of the while statement in Python:

while 判断条件:
    statements

Also pay attention to colons and indentations. A lso, there is no do in Python. W hile loop.

The following example uses while to calculate the sum of 1 to 100:

#!/usr/bin/env python3

n = 100

sum = 0
counter = 1
while counter <= n:     sum = sum + counter     counter += 1  print("Sum of 1 until %d: %d" % (n,sum)) 

The results are as follows:

Sum of 1 until 100: 5050

The for statement

The Python for loop can traverse any sequence of items, 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 loop instance:

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

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

#!/usr/bin/env python3
edibles = ["ham", "spam","eggs","nuts"]
for food in edibles:
    if food == "spam":
        print("No more spam please!")
        break
    print("Great, delicious " + food)
else:
    print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")

After executing the script, the loop body jumps out when the loop is "spam":

Great, delicious ham
No more spam please!
Finally, I finished stuffing myself

Range() function

If you need to traverse a sequence of numbers, you can use the built-in range() function. I t generates several columns, such as:

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

You can also use range to specify the value of the interval:

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

    
5
6
7
8
>>>

You can also have the range start with a specified number and specify a different increment (even a negative number; S ometimes this is also called 'step'):

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

    
0
3
6
9
>>> 

Negative:

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

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb

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

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

Break and continue statements and else clauses in loops

The break statement can jump out of the loop body of for and while. I f you terminate from a for or while loop, any corresponding loop else blocks will not be executed.

The continue statement is used to tell Python to skip the current loop and proceed to the next loop.

A loop statement can have an else clause, which is executed when the exhausting list (for loop) or a condition becomes false (with while loop) when the loop is terminated, but not when the loop is terminated by break, as in the following example of a loop looking for prime numbers:

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n//x)
...             break
...     else:
...         # 循环中没有找到元素
...         print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

Pass statement

Pass statement does nothing. I t requires only one statement syntax but is used when the program does not need any action. F or example:

>>> while True:
...     pass  # 等待键盘中断 (Ctrl+C)

Smallest class:

>>> class MyEmptyClass:
...     pass