python › Python Loops
phoolchandra · Oct 23, 2026 · Published
Want to print "Hello" 100 times, add marks of 60 students, or keep asking for a password until it is correct? Writing the same line again and again is not programming — loops are. In this blog you will master Python's for and while loops, the range() function, break, continue, pass, the loop else clause, nested loops and pattern programs.
Watch the video first, then use this blog as your notes. Every section has runnable examples, and at the end you will find a "Predict the Output" quiz, practice challenges, a self-check list, interview questions and a quick summary.
How to use this blog: Open the Python shell (type python in your terminal) or any online Python editor and type every example yourself. Change the values, break the code and see what happens — that is how concepts really stick.
A loop repeats a block of code multiple times. Each repetition is called an iteration.
# Without a loop
print("Hello")
print("Hello")
print("Hello")
# With a loop
for i in range(3):
print("Hello")| for loop | while loop |
|---|---|
| Repeats for each item in a sequence | Repeats as long as a condition is True |
| Used when the number of iterations is known | Used when the number of iterations is unknown |
| Example: print each student's name | Example: keep asking until the password is correct |
| Stops automatically at the end of the sequence | You must make the condition False, or it runs forever |
Syntax:
while condition:
# body - runs again and again while condition is Truecount = 1
while count <= 5:
print("Count:", count)
count += 1 # update - very important!
print("Loop finished")Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop finishedInfinite loop warning: If you forget count += 1, the condition stays True forever and the program never stops. Press Ctrl + C in the terminal to stop it.
password = ""
while password != "python123":
password = input("Enter password: ")
print("Access granted!")n = 12345
rev = 0
while n > 0:
digit = n % 10 # last digit
rev = rev * 10 + digit
n = n // 10 # remove last digit
print(rev) # 54321A for loop goes through each item of a sequence (list, string, tuple, dict, range...) one by one.
fruits = ["apple", "mango", "kiwi"]
for fruit in fruits:
print("I like", fruit)
for ch in "Hi":
print(ch) # H, then i
student = {"name": "Riya", "age": 17}
for key, value in student.items():
print(key, "->", value)range(start, stop, step) generates numbers from start up to but not including stop.
| Call | Numbers generated |
|---|---|
| range(5) | 0, 1, 2, 3, 4 |
| range(1, 6) | 1, 2, 3, 4, 5 |
| range(2, 10, 2) | 2, 4, 6, 8 |
| range(10, 0, -3) | 10, 7, 4, 1 |
| range(5, 0, -1) | 5, 4, 3, 2, 1 |
# Sum of 1 to 10
total = 0
for i in range(1, 11):
total += i
print(total) # 55
# Multiplication table of 5
for i in range(1, 11):
print(f"5 x {i:>2} = {5 * i}")| Statement | What it does |
|---|---|
| break | Exits the loop immediately |
| continue | Skips the rest of this iteration and moves to the next one |
| pass | Does nothing — a placeholder |
# break - stop at the first number divisible by 7
for n in range(1, 50):
if n % 7 == 0:
print("Found:", n) # Found: 7
break
# continue - skip 3
for i in range(5):
if i == 3:
continue
print(i, end=" ") # 0 1 2 4
# pass - placeholder
for i in range(3):
pass # will write code laterA loop can have an else block. It runs only if the loop finished without hitting break.
nums = [1, 3, 5, 7]
for n in nums:
if n % 2 == 0:
print("Found an even number")
break
else:
print("No even number found") # this runsPerfect for search problems — for example, checking if a number is prime:
n = 29
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
print(n, "is not prime")
break
else:
print(n, "is prime") # 29 is primeA loop inside another loop. The inner loop runs completely for every single iteration of the outer loop.
for i in range(1, 4):
for j in range(1, 4):
print(i * j, end=" ")
print()1 2 3
2 4 6
3 6 9n = 4
# Right triangle
for i in range(1, n + 1):
print("*" * i)
# Pyramid
for i in range(1, n + 1):
print(" " * (n - i) + "*" * (2 * i - 1))
# Number triangle
for i in range(1, n + 1):
for j in range(1, i + 1):
print(j, end=" ")
print()*
**
***
****
*
***
*****
*******
1
1 2
1 2 3
1 2 3 4names = ["Aman", "Riya", "Karan"]
marks = [88, 95, 76]
for i, name in enumerate(names, start=1): # index + value
print(i, name)
for name, mark in zip(names, marks): # loop two lists together
print(name, mark)
for name in reversed(names): # reverse order
print(name)
squares = [x * x for x in range(1, 6)] # list comprehension
print(squares) # [1, 4, 9, 16, 25]Don't modify a list while looping over it: Removing items from a list inside for x in my_list skips elements. Loop over a copy (my_list[:]) or build a new list with a comprehension.
import random
secret = random.randint(1, 20)
attempts = 0
while True:
guess = int(input("Guess a number (1-20): "))
attempts += 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print(f"Correct! You guessed it in {attempts} attempts.")
breakDon't run the code yet! Write your answers in a notebook, then check the Answers section at the end of this blog.
Q1. What is the output?
for i in range(3):
pass
print(i)Q2. What is the output?
i = 0
while i < 5:
i += 2
print(i)Q3. What is the output?
print(list(range(10, 0, -3)))Q4. What is the output?
for i in range(5):
if i == 3:
break
print(i, end=" ")Q5. What is the output?
for n in [2, 4, 6]:
if n == 5:
break
else:
print("done")Q6. How many times is "Hi" printed?
for i in range(3):
for j in range(4):
print("Hi")Q7. What is the output?
x = 10
while x > 0:
x -= 3
print(x)Solve these from easy to tricky:
Solutions for challenges 2, 4 and 5 are in the Answers section.
Tick off each skill once you are confident:
Q: Difference between for and while loops?
for iterates over a sequence and is used when the number of iterations is known; while repeats as long as a condition is True.
Q: Does Python have a do-while loop?
No. You can simulate it with while True: and a break at the end of the body.
Q: Difference between break and continue?
break exits the loop completely; continue skips only the current iteration.
Q: When does the else block of a loop execute?
When the loop ends normally — i.e. without encountering a break.
Q: What does range() return?
A range object — a memory-efficient, immutable sequence that produces numbers on demand.
| Concept | Syntax / Key point |
|---|---|
| for loop | for x in items: |
| while loop | while cond: |
| Count 0-4 | for i in range(5): |
| Reverse count | range(5, 0, -1) |
| Exit loop | break |
| Skip | continue |
| Index + value | enumerate(items) |
# Challenge 2 - factorial
n = 5
fact = 1
while n > 1:
fact *= n
n -= 1
print(fact) # 120
# Challenge 4 - Fibonacci
terms = 8
a, b = 0, 1
for _ in range(terms):
print(a, end=" ") # 0 1 1 2 3 5 8 13
a, b = b, a + b
print()
# Challenge 5 - sum of digits
num = 1234
total = 0
while num > 0:
total += num % 10
num //= 10
print(total) # 10Loops give your programs superpowers — they can now repeat any task thousands of times in a second. Next, learn Python Functions to organise your code into reusable blocks.
If this blog helped you, watch the full video above, subscribe to the channel and share it with a friend who is learning Python. Happy coding!