Python Basics

While Loop in Python

A while loop repeats as long as its condition remains true, making it useful when the iteration count is not known in advance.

What is While Loop?

A while loop repeats as long as its condition remains true, making it useful when the iteration count is not known in advance.

Run a Python while loop and learn how its condition controls repetition.

When should you use it?

  • Learn Python syntax through a practical example.
  • Build a foundation for larger programming problems.
  • Test an idea quickly without a local setup.

Example code

Run code →
main.py
countdown = 3

while countdown > 0:
    print(countdown)
    countdown -= 1

print("Go!")

Expected output

3
2
1
Go!

How it works

The counter changes during every iteration. Without that update, the condition would remain true and create an infinite loop.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in Python IDE →