SoFunction
Updated on 2024-12-13

Explaining the while infinite iteration loop method in Python

preamble

Python has while statements and for statements as loops. While the for statement has a certain number of processes, the while statement is a 'until the condition is met' type of loop.

For infinite iteration while, the number of times the loop executes is not explicitly specified in advance. Instead, the block is repeated as long as certain conditions specified are met.

Using Define Iteration for, the number of times a given block will be executed is specified explicitly at the beginning of the loop.

In addition to the general characteristics of while statements, Python has its own specifications, such as the lack of support for do while statements. Loop processing is a basic syntax of programming.

while loop

while <Boolean-calculated expression>.
<Executed python statement> # Loop body

Control expressions , <Boolean-calculated expressions> usually involve one or more variables that are initialized before starting the loop and then may be modified somewhere in the loop body.

When while encounters a loop, it is first evaluated in the Boolean context <Boolean-calculated expression>.

n = 5
while n > 0:
    n -= 1
    print(n)

Output:

4
3
2
1
0

while first tests the control expression of the loop. Assuming a false start, the loop body will never be executed.

n = 5
while n > 5:
    n -= 1
    print(n)

The break statement and continue statement

The entire body of the while loop is executed at each iteration, and Python provides two keywords for terminating loop iterations prematurely.

  • The break statement immediately terminates the loop completely. Program execution continues to the first statement after the loop body.
  • The continue statement immediately terminates the current loop iteration. Execution jumps to the top of the loop and re-evaluates the control expression to determine whether the loop executes again or terminates.

# break Examples
n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)
print('End of loop.')

Output:

4
3
The cycle ends.

# continue Examples
n = 5
while n > 0:
    n -= 1
    if n == 2:
        continue
    print(n)
print('End of loop.')

Output:

4
3
1
0
The cycle ends.

else clause

Python allows optional clauses at the end of a loop else.

while <Boolean expressions>:
    <executedpythonstatement> # Loop body
else:
    <循环终止后执行statement>

n = 5
while n > 0:
    n -= 1
    print(n)
else:
    print('Loop done.')

Output:

4
3
2
1
0
Loop done.

# If there's a break, it won't be executed twice in some cases.
n = 5
while n > 0:
    n -= 1
    print(n)
    if n == 2:
        break
else:
    print('End of loop.')

Output:

4
3
2

infinite loop

Suppose a while theoretically never ending loop is written.

while True:
    print('True Three Kingdoms')

true·Three Kingdoms
true·Three Kingdoms
  .
  .
  .
true·Three Kingdoms

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyboardInterrupt

Such a loop can only be stopped manually.

Single actually has its applications, such as looping through the elements of a list.

list_ = ['True Three Kingdoms', 'True Three Kingdoms', 'True Three Kingdoms']
while True:
    if not list_ :
        break
    print(list_ .pop(-1))

Output:

True Three Kingdoms
True Three Kingdoms
True Three Kingdoms

You can break to specify multiple statements in a loop. You can break to end the loop at several different points without having to specify all the termination conditions in the loop header.

while True:
if <Boolean calculated expression 1>: # Conditional judgment 1
        break
    
if <Boolean calculated expression 2>: # Conditional judgment 2
        break
    
if <Boolean-calculated expression 3>: # Conditional judgment 3
        break

nested while loop

Python control structures can be nested within each other.

if age < 18:
    if gender == 'M':
        print('Sub-supply')
    else:
        print('Mother')
elif age >= 18 and age < 65:
    if gender == 'M':
        print('Father')
    else:
        print('Mother')
else:
    if gender == 'M':
        print('おじいさん')
    else:
        print('Grandmother')

A while loop can be contained within another while loop.

list_ = ['Father', 'Mother']
while len(list_ ):
    print(list_.pop(0))
    list__ = ['おじいさん', 'Grandmother']
    while len(list__ ):
        print('>', list__.pop(0))

Output:

Father.
> おじいさん
> Grandmother
Mother
> おじいさん
> Grandmother

The break statement found in a nested loop applies to the closest closed loop.

while <Boolean expressions1>:
    statement
    statement

    while <Boolean expressions2>:
        statement
        statement
        break  # Expressions for while <Boolean calculations2>: loops

    break  # Expression 1 for while <Boolean calculation>: loop

While loops can be nested within if, elif, and else statements.

if <Boolean calculated expression 1>.
<python execution statement 1>
while <Boolean computation of expression 2>.
<python execution statement 2>.
<python execution statement 3>.
else:
while <Boolean computed expression 3>.
<python executing statement 4>
<python execution statement 5>.
<python executing statement 6>

while <Boolean computation of expression 1>.
if <Boolean-calculated expression 2>.
<python execution statement 1>
elif <Boolean computed expression 3>:.
<python execution statement 2>.
    else:
<python execution statement 3>.
if <Boolean-calculated expression 4>.
<python executing statement 4>

Single line while loop

Like the if statement, while can specify a loop on a single line. You can also form multiple loop body statements with ;.

n = 5
while n > 0: n -= 1; print(n)

Output:

4
3
2
1
0

It is not acceptable to combine two compound statements in a shorthand way.

if True: print('data')
data

while n > 0: n -= 1; if True: print('data')
SyntaxError: invalid syntax

Above is a detailed explanation of the while infinite iteration loop method in Python details, more information about Python while infinite iteration please pay attention to my other related articles!