Python Tutorial

Introduction

Edit Template
  • Home
  • /
  • Python while Loop

Python Tutorial

Introduction

Edit Template
  • Home
  • /
  • Python while Loop

while Loop in Python

The while loop is used when you want to repeat a block of code as long as a condition stays true. The loop will continue running until that condition becomes false.

Basic while Loop

Let’s say you want to count down from 5 to 1. Here’s how you can do that using a while loop:

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

				
			

Output:

				
					5
4
3
2
1

				
			

In this example:

  • The loop runs while count is greater than 0.

  • After each loop, we decrease count by 1.

  • Eventually, the condition becomes false and the loop stops.

Important:
Make sure the condition eventually becomes false, otherwise the loop will keep running forever.

Using else with while

Python also allows an else block to run after the while loop ends. This is useful when you want to run some code once the loop has finished properly.

				
					x = 5
while x > 0:
    print(x)
    x = x - 1
else:
    print("Countdown complete.")

				
			

Output:

				
					5
4
3
2
1
Countdown complete.

				
			

The else block is triggered only after the while loop condition becomes false.

Summary

  • Use while loops when the number of iterations is not fixed.

  • Always update the condition variable to avoid an infinite loop.

  • else runs when the loop exits normally (not via a break).

Scroll to Top