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

Python, while loop is used for performing an indefinite iteration. 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.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.