⚡0 XP🔥0

while Loop

Lesson 10 of 33 ⏱ 4 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs Python

Repeat code while a condition is true - counters, accumulators, input validation, infinite loops and while-else.

What is a loop?#

A loop repeats a block of code. Without loops, printing numbers 1 to 100 would need 100 print() lines. With a loop, it takes three.

Python has two loops:

  • while - repeats as long as a condition is True.
  • for - repeats for each item in a sequence (next lesson).

Syntax#

while condition:
    # body - runs again and again while condition is True

How it works:

  1. Check the condition.
  2. If True → run the body, then go back to step 1.
  3. If False → skip the body and continue after the loop.
▶ Try it YourselfPython
Ctrl + Enter to run

The three parts of a counting loop#

Every counting while loop needs three things:

Part Example Purpose
Initialise i = 1 starting value
Condition while i <= 5: when to keep going
Update i += 1 move towards the end
हिंदी में समझें

while loop को ऐसे समझें: "जब तक (while) condition सही है, तब तक यह काम करते रहो।"

हर counting loop में तीन चीज़ें ज़रूरी हैं:

  1. शुरुआत (initialise) - जैसे i = 1
  2. शर्त (condition) - जैसे i <= 5
  3. बदलाव (update) - जैसे i += 1

अगर आप तीसरा हिस्सा (update) भूल गए, तो i हमेशा 1 ही रहेगा, condition हमेशा True रहेगी, और loop कभी खत्म नहीं होगा - इसे infinite loop कहते हैं।

Tracing a loop step by step#

total = 0
i = 1
while i <= 4:
    total += i
    i += 1
print(total)
Step i condition i <= 4 total after step
1 1 True 1
2 2 True 3
3 3 True 6
4 4 True 10
5 5 False → stop 10
Tip

When a loop gives an unexpected answer, trace it on paper like this table, or add a print(i, total) inside the loop to see each step.

Common patterns#

Accumulator (sum / product)#

▶ Try it YourselfPython
Ctrl + Enter to run

Counting digits#

▶ Try it YourselfPython
Ctrl + Enter to run

Input validation - repeat until valid#

▶ Try it YourselfPython
Ctrl + Enter to run
choice = ""
while choice != "3":
    print("1. Deposit  2. Withdraw  3. Exit")
    choice = input("Choose: ")
    if choice == "1":
        print("Depositing...")
    elif choice == "2":
        print("Withdrawing...")
print("Thank you!")

Infinite loops#

A loop whose condition never becomes False runs forever:

i = 1
while i <= 5:
    print(i)       # forgot i += 1 -> prints 1 forever

On your computer, press Ctrl + C to stop it. (Our browser editor stops it automatically after a few seconds.)

Sometimes infinite loops are intentional - servers and games run while True: and exit with break:

▶ Try it YourselfPython
Ctrl + Enter to run

You'll learn break and continue in detail in a later lesson.

while...else#

A while loop can have an else block. It runs only if the loop ended normally - i.e. the condition became False, not because of break.

▶ Try it YourselfPython
Ctrl + Enter to run

Summary#

  • while condition: repeats the body as long as the condition is True.
  • Counting loops need: initialise → condition → update.
  • Forgetting the update causes an infinite loop (stop with Ctrl + C).
  • while True: + break is a common pattern for "repeat until...".
  • while...else: the else runs only when the loop wasn't broken.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Count down

Read a number n and print a countdown from n to 1, then print Go!.

Test input:
5
Expected output:
5
4
3
2
1
Go!
2

Sum until zero

Keep reading numbers (one per line) until the user enters 0. Then print the total of all the numbers entered.

Test input:
12
7
30
0
Expected output:
49
3

Reverse a number

Read a positive integer and print its digits reversed as a number, using a while loop with % and //. For 1234 print 4321.

Test input:
1234
Expected output:
4321

Quick Quiz

Q1.

How many times does this print?

i = 1
while i <= 5:
    print(i)
    i += 2
Q2.

What happens if you forget i += 1 in a counting while loop?

Q3.

When does the else block of a while loop run?

Q4.

What is printed?

n = 0
while n < 3:
    n += 1
print(n)
Q5.

Which loop is best when you don't know in advance how many times to repeat (e.g. until the user types 'quit')?