While Loop in Python

A while loop in Python is used to repeat a block of code as long as a condition is true. It is useful when we don’t know in advance how many times we want to run the loop.

The condition is checked before every loop cycle. If it's true, the code inside the loop runs. If it's false, the loop stops.

Syntax:

while condition:
    # block of code

Note: Just like in for loop, indentation is important in while loop to define which code belongs inside the loop.

Example 1: Print numbers from 1 to 5 using while loop

i = 1
while i <= 5:
    print(i)
    i += 1

Output:

1

2

3

4

5

Explanation:

  • We start with i = 1.
  • The loop condition is i <= 5, which means the loop will run while i is 5 or less.
  • Inside the loop, print(i) displays the current value of i.
  • Then i += 1 increases i by 1.
  • When i becomes 6, the condition is false and the loop stops.

Why We Use while Loop?

  • When we don’t know how many times: Use while loop if the number of repetitions is not fixed.
  • Based on a condition: It repeats only as long as a condition is true.
  • Useful in many real-life scenarios: Like waiting for user input, retrying until successful, etc.

Example 2: Real-life style – countdown timer

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

Output:

Countdown: 5

Countdown: 4

Countdown: 3

Countdown: 2

Countdown: 1

Explanation:

  • We start with count = 5.
  • The loop checks if count > 0.
  • Each time, it prints the countdown message and decreases count by 1.
  • When count becomes 0, the loop stops.

Summary:

  • Used when: The number of repetitions is unknown and depends on a condition.
  • Syntax: while condition:
  • Condition checked: Before every iteration.
  • Loop stops: When the condition becomes false.

Welcome to ShikshaSanchar!

ShikshaSanchar is a simple and helpful learning platform made for students who feel stressed by exams, assignments, or confusing topics. Here, you can study with clarity and confidence.

Here, learning is made simple. Notes are written in easy English, filled with clear theory, code examples, outputs, and real-life explanations — designed especially for students like you who want to understand, not just memorize.

Whether you’re from school, college, or someone learning out of curiosity — this site is for you. We’re here to help you in your exams, daily studies, and even to build a strong base for your future.

Each note on this platform is carefully prepared to suit all levels — beginner to advanced. You’ll find topics explained step by step, just like a good teacher would do in class. And the best part? You can study at your pace, anytime, anywhere.

Happy Learning! – Team ShikshaSanchar