Home Blogs All Courses
python c OA ( Online Assessment ) Amazon Web Services (AWS) leetcode dsa algorithms java Machine learning
Get Referral
Login Sign Up

python › Python Loops

Python Loops: for Loop, while Loop, break, continue & range() Explained

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.

1. What is a Loop?

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 loopwhile loop
Repeats for each item in a sequenceRepeats as long as a condition is True
Used when the number of iterations is knownUsed when the number of iterations is unknown
Example: print each student's nameExample: keep asking until the password is correct
Stops automatically at the end of the sequenceYou must make the condition False, or it runs forever

2. The while Loop

Syntax:

while condition:
    # body - runs again and again while condition is True
count = 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 finished

Infinite 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.

Real-world example: password check

password = ""
while password != "python123":
    password = input("Enter password: ")
print("Access granted!")

Example: reverse a number

n = 12345
rev = 0
while n > 0:
    digit = n % 10        # last digit
    rev = rev * 10 + digit
    n = n // 10           # remove last digit
print(rev)                # 54321

3. The for Loop

A 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)

4. The range() Function

range(start, stop, step) generates numbers from start up to but not including stop.

CallNumbers 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}")

5. break, continue and pass

StatementWhat it does
breakExits the loop immediately
continueSkips the rest of this iteration and moves to the next one
passDoes 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 later

6. The Loop else Clause (A Hidden Python Feature)

A 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 runs

Perfect 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 prime

7. Nested Loops

A 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 9

Pattern programs (very popular in exams and interviews)

n = 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 4

8. Pythonic Looping Tricks

names = ["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.

9. Mini Project: Number Guessing Game

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.")
        break

Quiz: Predict the Output

Don'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)

Practice Challenges

Solve these from easy to tricky:

  1. Print all even numbers from 1 to 50 using a for loop.
  2. Find the factorial of a number using a while loop.
  3. Count the vowels in a string entered by the user.
  4. Print the Fibonacci series up to n terms.
  5. Find the sum of digits of a number (e.g. 1234 → 10).
  6. Print an inverted star triangle of 5 rows.

Solutions for challenges 2, 4 and 5 are in the Answers section.

Self-Check: Can You Do This?

Tick off each skill once you are confident:

Frequently Asked Interview Questions

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.

Summary

  • while repeats while a condition is True — always update the variable to avoid infinite loops.
  • for iterates over any sequence: list, string, tuple, dict, range.
  • range(start, stop, step) excludes stop.
  • break exits, continue skips, pass does nothing.
  • Loop else runs only if no break happened.
  • Use enumerate, zip and comprehensions for Pythonic loops.

Quick Revision Cheat Sheet

ConceptSyntax / Key point
for loopfor x in items:
while loopwhile cond:
Count 0-4for i in range(5):
Reverse countrange(5, 0, -1)
Exit loopbreak
Skipcontinue
Index + valueenumerate(items)

Answers

Quiz answers

  1. 2 – the loop variable keeps its last value.
  2. 6
  3. [10, 7, 4, 1]
  4. 0 1 2
  5. done – break never ran, so else runs.
  6. 12 – 3 × 4.
  7. -2 – 10 → 7 → 4 → 1 → -2.

Challenge solutions

# 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)                # 10

Conclusion

Loops 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!