DEV Community

SATHISHKUMAR R
SATHISHKUMAR R

Posted on

While Loop in Python

A while loop is used to execute a block of code repeatedly as long as the condition is True.

Syntax:

while condition:
statement

Example:
Print 1 to 5

i = 1
while i <= 5:

print(i)

i += 1

Output:
1
2
3
4
5

Explanation:

  • i = 1 – Starting value.
  • while i <= 5 – Checks the condition.
  • print(i) – Prints the number.
  • i += 1 – Increases the value by 1.

Real-time Example: A student keeps attempting a quiz until they get the correct answer. The while loop continues until the condition becomes False.

Top comments (0)