Python3 loop statement


This chapter will introduce you to the use of Python loop statements.

Loop statements in Python include for and while.

The control structure diagram of the Python loop statement is as follows:

1028.png


while loop

The general form of the while statement in Python :

while 判断条件:
    语句

Also need to pay attention to colon and indentation. Also, there is no do..while loop in Python.

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("1 到 %d 之和为: %d" % (n,sum))

The execution result is as follows:

1 到 100 之和为: 5050

Infinite loop

We can set conditions by The expression is never false to achieve an infinite loop. The example is as follows:

#!/usr/bin/python3

var = 1
while var == 1 :  # 表达式永远为 true
   num = int(input("输入一个数字  :"))
   print ("你输入的数字是: ", num)

print ("Good bye!")

Execute the above script and the output result is as follows:

输入一个数字  :5
你输入的数字是:  5
输入一个数字  :

You can use CTRL+C to exit the current infinite loop.

Infinite loops are very useful for real-time requests from clients on the server.

while loop uses else statement

In while...else, execute the else statement block when the conditional statement is false:

#!/usr/bin/python3

count = 0
while count < 5:
   print (count, " 小于 5")
   count = count + 1
else:
   print (count, " 大于或等于 5")

Execute the above script, the output result is as follows:

0  小于 5
1  小于 5
2  小于 5
3  小于 5
4  小于 5
5  大于或等于 5

Simple statement group

Similar to the syntax of if statement, if there is only one statement in your while loop body, you can write the statement and while in the same line, as follows:

#!/usr/bin/python

flag = 1

while (flag): print ('欢迎访问php中文网!')

print ("Good bye!")

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

Execute the above script, the output result is as follows:



for statement

Python for loop can traverse any sequence of items, such as a list or a string.

The general format of a for loop is as follows:

for <variable> in <sequence>:
    <statements>
else:
    <statements>

Python loop loop example:

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

The break statement is used in the following for examples, and the break statement is used to jump out of the current loop body:

#!/usr/bin/python3

sites = ["Baidu", "Google","php","Taobao"]
for site in sites:
    if site == "php":
        print("php中文网!")
        break
    print("循环数据 " + site)
else:
    print("没有循环数据!")
print("完成循环!")

After executing the script, the loop body will jump out when looping to "php":

循环数据 Baidu
循环数据 Google
php中文网!
完成循环!

range() function

If you need to traverse a sequence of numbers, You can use the built-in range() function. It will generate a sequence, for example:

>>> 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 make the range start with a specified number and specify a different increment (even a negative number , sometimes this is also called 'step size'):

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

    
0
3
6
9
>>>

Negative numbers:

>>> for i in range(-10, -100, -30) :
    print(i)

    
-10
-40
-70
>>>

You can combine the range() and len() functions to iterate over the indices of a sequence, as follows:

>>> a = ['Google', 'Baidu', 'php', 'Taobao', 'QQ']
>>> for i in range(len(a)):
...     print(i, a[i])
... 
0 Google
1 Baidu
2 php
3 Taobao
4 QQ
>>>

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

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

break and continue statements and the else clause in the loop

The break statement can jump out of the for and the body of the while loop. If you terminate from a for or while loop, any corresponding loop else blocks will not execute. An example is as follows:

#!/usr/bin/python3

for letter in 'php':     # 第一个实例
   if letter == 'b':
      break
   print ('当前字母为 :', letter)
  
var = 10                    # 第二个实例
while var > 0:              
   print ('当期变量值为 :', var)
   var = var -1
   if var == 5:
      break

print ("Good bye!")

The output result of executing the above script is:

当前字母为 : R
当前字母为 : u
当前字母为 : n
当前字母为 : o
当前字母为 : o
当期变量值为 : 10
当期变量值为 : 9
当期变量值为 : 8
当期变量值为 : 7
当期变量值为 : 6
Good bye!

The continue statement is used to tell Python to skip the remaining statements in the current loop block and then continue with the next round of loops.

#!/usr/bin/python3

for letter in 'php':     # 第一个实例
   if letter == 'o':        # 字母为 o 时跳过输出
      continue
   print ('当前字母 :', letter)

var = 10                    # 第二个实例
while var > 0:              
   var = var -1
   if var == 5:             # 变量为 5 时跳过输出
      continue
   print ('当前变量值 :', var)
print ("Good bye!")

The output result of executing the above script is:

当前字母 : R
当前字母 : u
当前字母 : n
当前字母 : b
当前变量值 : 9
当前变量值 : 8
当前变量值 : 7
当前变量值 : 6
当前变量值 : 4
当前变量值 : 3
当前变量值 : 2
当前变量值 : 1
当前变量值 : 0
Good bye!

The loop statement can have an else clause, which causes a loop in the exhaustive list (in a for loop) or when the condition becomes false (in a while loop) It is executed when terminated, but not executed when the loop is terminated by break.

The following example is a loop example for querying prime numbers:

#!/usr/bin/python3

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, '等于', x, '*', n//x)
            break
    else:
        # 循环中没有找到元素
        print(n, ' 是质数')

The output result of executing the above script is:

2  是质数
3  是质数
4 等于 2 * 2
5  是质数
6 等于 2 * 3
7  是质数
8 等于 2 * 4
9 等于 3 * 3

pass statement

Python pass is an empty statement , in order to maintain the integrity of the program structure.

pass does not do anything and is generally used as a placeholder statement. The following example is

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

The smallest class:

>>> class MyEmptyClass:
...     pass

The following example executes the pass statement block when the letter is o :

#!/usr/bin/python3

for letter in 'php': 
   if letter == 'o':
      pass
      print ('执行 pass 块')
   print ('当前字母 :', letter)

print ("Good bye!")

The output result of executing the above script is:

当前字母 : R
当前字母 : u
当前字母 : n
执行 pass 块
当前字母 : o
执行 pass 块
当前字母 : o
当前字母 : b
Good bye!