Coding Now – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 9667708830
Back to Python Notes
Topic #5

Loops in Python

Why Do We Need Loops?

Loops let you repeat a block of code multiple times without writing it again and again. Python has two main types: the for loop and the while loop.

The for Loop

A for loop iterates over a sequence — a list, tuple, string, or range of numbers.

for i in range(5):
    print(i)
# Output: 0 1 2 3 4
courses = ["Python", "Data Science", "AI"]
for course in courses:
    print("Course:", course)

Understanding range()

range(5)         # 0, 1, 2, 3, 4
range(2, 6)       # 2, 3, 4, 5
range(0, 10, 2)   # 0, 2, 4, 6, 8 (step of 2)

The while Loop

A while loop keeps running as long as its condition stays True.

count = 1
while count <= 5:
    print(count)
    count += 1

Careful: if the condition never becomes False, you'll create an infinite loop that never stops on its own.

Loop Control Statements

break — exits the loop immediately

for num in range(10):
    if num == 5:
        break
    print(num)
# Output: 0 1 2 3 4

continue — skips the current iteration

for num in range(5):
    if num == 2:
        continue
    print(num)
# Output: 0 1 3 4

else with loops

Python lets you attach an else block to a loop — it runs only if the loop finishes without hitting a break.

for num in range(3):
    print(num)
else:
    print("Loop finished without break")

Nested Loops

for i in range(3):
    for j in range(2):
        print(i, j)

for vs while — Which One to Use?

  • Use for when you know how many times to loop, or you're iterating over a collection
  • Use while when the loop should continue until some condition changes — the number of iterations isn't known upfront

Key Takeaways

  • for loops iterate over sequences; while loops run based on a condition
  • break exits a loop early, continue skips to the next iteration
  • Always make sure a while loop's condition will eventually become False to avoid infinite loops

Want to go beyond the notes?

Join CodingNow's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →