Python program flow control statement: while loop


while loop

Python uses while loops to process loops that meet certain conditions. While loops are generally not used to deal with iterable objects, while loop statements can achieve infinite loops.

Basic structure of while loop

The while loop is often used to process loops that meet certain conditions. The syntax is as follows:

while condition:
    statements
    ……
else:
	statements

The condition is judged once in each loop. When the return value of the condition is True, it enters the while loop to execute the statements. When the return value of the condition is False, the statements under the while are not executed, and the statements under the else are executed, where the else can be omitted. If the return value of condition is always True, the while loop becomes an infinite loop, also called an "infinite loop". The flow chart of while loop execution is shown in the figure:

insert image description here

An example is as follows:

Example: Count the number of odd numbers between 1 and 100

i = 1 # 开始值
count = 0 # 统计频数
while i <= 100: # 结束条件
	if i % 2 != 0: # 如果满足不能被2整除的条件
		count += 1 # count加1
		i += 1 # 增减量,如果没有增减量则i=1一直成立,成为死循环
	print('1~100之间有{}个奇数'.format(count))

1~100之间有50个奇数

Note: The three elements of the while loop: the start value, the end condition, and the increase or decrease. If there is no increase or decrease, the start value will not change, the end condition will always return True, and the while will become an infinite loop.

Nested use of while loops

Python allows the use of while loops inside while loops. For example, to print the nine-nine multiplication table, the example is as follows:

a = 1  # 外层循环的开始值
while a < 10:  # 外层循环的结束条件
    b = 1  # 内层循环的开始值
    while b <= a:  # 内层循环的结束条件
        print('%d*%d=%2d' % (a, b, a * b), end=' ')  # 打印,打印完后不换行
        b += 1  # 内层循环的增减量
    print()  # 内层结束后进行换行
    a += 1  # 外层循环的增减量

The output after running is as follows:

1*1= 1 
2*1= 2 2*2= 4 
3*1= 3 3*2= 6 3*3= 9 
4*1= 4 4*2= 8 4*3=12 4*4=16 
5*1= 5 5*2=10 5*3=15 5*4=20 5*5=25 
6*1= 6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 
7*1= 7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 
8*1= 8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 
9*1= 9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81 

Both for loops and while loops can implement looping functions, but for loops are often used to loop iterable objects, that is, when the end is known. While loops are often used when the ending is unknown. These two kinds of loops can be nested, but it should be noted that the efficiency of nested loops is not very high. The nested loops actually perform Cartesian product operations. If the number of loops is large, the waiting time will be longer.

infinite while loop

In some cases, it is necessary to use an infinite loop, which is an infinite loop. This requirement can be achieved by using a while loop. As long as the condition after while is always fixed to a true value, the example is as follows:

import time

while True:
    print('这是一个无限循环')
    time.sleep(1)

Output result:

这是一个无限循环
这是一个无限循环
这是一个无限循环
这是一个无限循环
这是一个无限循环
....

The infinite loop cannot be stopped automatically in the editor. It can only be stopped manually. In the PyCharm editor, the shortcut key Ctrl+C can be used to stop the loop.

loop control statement

In order to better control the loop, you can use the break and continue statements in the for loop and while loop to control the loop.

break statement

The break statement is used to jump out of the current loop, that is, to end the loop early, and the else will also be skipped. An example is as follows:

# 统计1~100之间奇数的个数
i = 1  # 开始值
count = 0
while True:  # 结束条件为True
    if i % 2 != 0:
        count += 1
    i += 1  # 增减量
    if i > 100:  # 满足if条件执行break语句
        break  # 跳出循环
else:
    print('while循环结束!')  # else也会被跳过,该句不执行
print('while循环由break语句跳出,else未执行!')
# while循环由break语句跳出,else未执行!
print(count)

operation result:

while循环由break语句跳出,else未执行!
50

Note: The break statement can also be used in nested loops. When used in the inner loop of a nested loop, it will only jump out of the inner loop and will not affect the outer loop to continue running.

continue statement

The continue statement is used to skip this loop and continue to the next loop. The example is as follows:

# 计算1~100之间能被3整除的数的和
total = 0
for i in range(1, 101):
    if i % 3 != 0:  # 条件:不能被3整除
        continue  # 如果满足以上条件就跳出本次循环,进行下一次循环
    total += i
print(total)

Output result:

1683

Guess you like

Origin blog.csdn.net/shield911/article/details/124208264