Python while Loop


The purpose of the loop is to allow code to be repeated. The most common application scenario for the while loop is to have the executed code repeat as many times as specified.

Related course: Complete Python Programming Course & Exercises

While loop syntax

Basic syntax of the while statement.

while True:
    print('hello python')

This outputs:

python-while-loop

Python while Loop examples

Processing conditions (counter +1) are required, otherwise the loop continues forever. The while statement and indentation is a complete block of code

while_1.py

    # _*_ coding:utf-8 _*_
    # Define an integer variable to record the number of cycles
    i = 0
    # Start the cycle
    while i<= 10:
        # Code that you want to execute within the loop
        print('hello python')
        # Process cycle count
        i += 1
    print('End of cycle, i = %d' %i)

The Python program outputs:.

python-while-loop-cycle

Example 1: Summation of numbers between 0 and 100 using the while loop

Code.

# 1. Define an integer variable to record the number of cycles
i = 0

# 2. Define the variables for the final calculation
sum = 0

# 3. Start the cycle
while i<=100:
    # equals sum=sum+i
    sum +=i
    # Process counters
    i +=1
print(f'Sum of numbers between 0 and 100: {sum}')

The Python program outputs:.

python-while-loop-counter

Example 2: Nested loops

For example: in the console output five lines of continuous *, the number of each planet in turn increases

As follows.

*
**
***
****
******

Code: (Method 1)

row = 1
while row <= 5:
    col = 1
    while col <= row:
        print('*',end='')
        col += 1
    print('')
    row +=1

The Python program outputs:.

python-while-loop-example

Code: (Method 2)

i = 1
while i <= 5:
    print('*' * i)
    i += 1
print('')

Try to output in reverse order, like this:

******
****
***
**
*

Code: (Method 1)

row = 1
while row <= 5:
    col = 1
    while col <= 6-row:
        print('*',end='')
        col += 1
    print('')
    row += 1

The Python program outputs:.

python-while-loop-triangle

Code: (Method 2)

j = 1
while j <= 5:
    print('*' * (6-j))
    j += 1
print('')

# end indicates the information output at the end
for i in range(5):
    print(i,end='')