Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Unit 1 — while Loop

Lesson 21 of 50 in the free Python Programming notes on Siksha Sarovar, written by Rohit Jangra.

while Loop

The while loop repeats a block as long as the condition remains True. Used when the number of iterations is not known in advance.

Syntax

while condition:
    statement(s)
i = 1
while i <= 5:
    print(i)
    i += 1

Output:

1
2
3
4
5
Important: the loop variable must be updated inside the body, or the loop never terminates (infinite loop).
# Infinite loop example (do NOT run without a break condition)
# while True:
#     print("runs forever")

while-else

n = 0
while n < 3:
    print(n)
    n += 1
else:
    print("Loop ended normally (no break)")

Example: Sum of digits using while

num = 1234
total = 0
while num > 0:
    total += num % 10
    num //= 10
print("Sum of digits:", total)   # 10

Example: Reverse a number

num = 1234
reverse = 0
while num > 0:
    digit = num % 10
    reverse = reverse * 10 + digit
    num //= 10
print("Reversed:", reverse)   # 4321

for vs while — when to use which

Use forUse while
Number of iterations is known / iterating a collectionNumber of iterations is unknown
Iterating strings, lists, rangesWaiting for a condition to change (e.g. user input, sentinel value)