Code / Python for Beginners / Unit 3: Loops

while loops while लूप

Lesson 7 of 14 · about 14 minutes · Repeat while a condition is True.

⚡ 0 XP

Step 1 of 2

Repeat while…

repeat× 4

A while loop repeats its indented block as long as its condition is True:

  1. check the condition
  2. if True, run the block, then go back to step 1
  3. if False, carry on after the loop

Something inside the loop must change, so the condition becomes False one day. If n never gets smaller, the loop runs forever (an infinite loop) and the program hangs. Always ask: what moves my loop towards the end?

Example
n = 3
while n > 0:
    print("Chai in", n)
    n = n - 1
print("Chai ready! ☕")

🎯 Challenge: ISRO countdown +15 XP

Read a number n. Use a while loop to print n, n-1, … down to 1, one number per line. After the loop the program prints Liftoff! 🚀 (already written). For 5 the numbers are 5, 4, 3, 2, 1.

Try twice to unlock the solution (0/2)

main.pyCtrl ⏎
Output

What your program prints appears here.

Checklist

Press Run to check your code.

  • Counts 5, 4, 3, 2, 1
  • Works from 3 too
  • Uses a while loop
Lesson notes (text version)

1. Repeat while…

A while loop repeats its indented block as long as its condition is True:

  1. check the condition
  2. if True, run the block, then go back to step 1
  3. if False, carry on after the loop

Something inside the loop must change, so the condition becomes False one day. If n never gets smaller, the loop runs forever (an infinite loop) and the program hangs. Always ask: what moves my loop towards the end?

                n = 3
while n > 0:
    print("Chai in", n)
    n = n - 1
print("Chai ready! ☕")
              

Challenge: ISRO countdown

Read a number n. Use a while loop to print n, n-1, … down to 1, one number per line. After the loop the program prints Liftoff! 🚀 (already written). For 5 the numbers are 5, 4, 3, 2, 1.

2. Loop until a goal

while is perfect when you don’t know how many times to repeat. "Keep saving until I have enough" is a while loop.

Use a counter variable to count the rounds: start it at 0 and add 1 each time through the loop.

Challenge: Gullak savings

You put the same amount in your gullak every week. Read weekly and the target. Use a while loop: while saved is less than target, add weekly to saved and 1 to weeks. For ₹150 a week and a ₹1000 target, print Weeks needed: 7 and Saved: ₹1050.

Search by task, format or tool name.