Back to Python Notes
Topic #200

Loops in Python

By the end of this lesson, you will be able to write efficient Python loops using for and while, control flow with break and continue, and handle nested iterations.

What it is

Loops are programming structures that allow a block of code to execute repeatedly. In Python, there are two primary types: the for loop, which iterates over a sequence (like a list or string), and the while loop, which repeats as long as a condition remains true. Related terms include iteration (one pass through the loop) and loop variable (the temporary variable holding the current item).

Why it matters

  • Efficiency: Eliminates repetitive code, making scripts shorter and easier to maintain.
  • Data Processing: Essential for iterating through lists, dictionaries, and files to transform or analyze data.
  • User Interaction: Allows programs to wait for valid input or run until a user decides to stop.
  • Algorithm Implementation: Fundamental for sorting, searching, and mathematical calculations.

Syntax or steps

The for loop syntax is for item in iterable:. The while loop syntax is while condition:. Both require an indented block of code to define what happens during each iteration. Use break to exit a loop immediately and continue to skip the rest of the current iteration and move to the next one.

Example

# For loop: Iterate over a list
numbers = [1, 2, 3, 4, 5]
total = 0

for num in numbers:
    if num == 3:
        continue  # Skip adding 3
    total += num

print(f"Sum excluding 3: {total}")

# While loop: Count down
count = 5
while count > 0:
    print(count)
    count -= 1
else:
    print("Countdown finished!")

# Nested loop: Multiplication table snippet
for i in range(1, 3):
    for j in range(1, 4):
        print(f"{i}x{j}={i*j}", end=" ")
    print()  # New line after inner loop completes

Explanation: The first block sums numbers but skips 3 using continue. The second block uses while to decrement a counter; the else clause runs only if the loop wasn't terminated by break. The third block demonstrates nesting, where the inner loop runs completely for each single iteration of the outer loop.

Common mistakes

  • Infinite Loops: Forgetting to update the condition variable in a while loop (e.g., missing count -= 1). Always ensure the condition eventually becomes false.
  • Indentation Errors: Python relies on whitespace. Code not indented under the loop header will not execute repeatedly.
  • Misusing break: Using break when you meant continue. break exits the entire loop, while continue just skips the current item.
  • Modifying Lists During Iteration: Changing the size of a list while looping over it can cause skipped items or errors. Iterate over a copy (list[:] ) instead.

When to use it

ScenarioRecommended LoopReason
Iterating over known collections (lists, strings)forCleaner syntax, automatic handling of indices/items.
Repeating until a dynamic condition changeswhileIdeal for user input validation or game loops.
Fixed number of repetitionsfor with range()Explicitly defines start, stop, and step values.

Practice

Guided Exercise: Write a for loop that prints all even numbers from 1 to 10. Hint: Use if num % 2 == 0.

Challenge: Create a program that asks the user for a password. Use a while loop to keep asking until they enter "secret". If they enter "quit", break the loop and print "Access denied."

Quick check

Question: What is the difference between break and continue?

Answer: break terminates the entire loop immediately, whereas continue skips the remaining code in the current iteration and proceeds to the next iteration.

Summary

Python loops provide powerful mechanisms for repetition. Choose for for sequences and while for conditional repetition. Mastering break and continue allows for precise control over execution flow, enabling complex logic like filtering data or managing user interactions efficiently.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Loops in Python – FAQs

Quick answers about learning Loops in Python in Python.

This free note from Coding Now Tech Institute explains Loops in Python in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including Loops in Python, is 100% free with no signup required.
With focused practice, most students grasp Loops in Python in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now