Skip to content

A while loop in Python is used for what type of iteration

  • by

Python, while loop is used for performing an indefinite iteration. That means repeatedly executing a section of code until a condition is met or no longer met. Where the number of times the loop will be executed, is not specified explicitly in advance.

While(condition):
{
    ....
        ...statement
increment or decrement
} 

How’s while loop works in Python:-

  • First initialise value to the variable
  • Then the statements inside the while loop will execute
  • Later increment or decrement statement will execute
  • This process will continue till the condition gets false.

Example while loop in Python

The while loop in python is used to iterate over a block of code until the condition is true.

# initialize sum and counter
res = 0
i = 1

while i <= 10:
    res = res + i
    i = i + 1  # update counter

# print the sum
print("The sum is", res)

Output:

A while loop in Python is used for what type of iteration

Do comment if you have any doubts and suggestions on this Python while loop question.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading