PythonLoops

Python Loops: for, while, and Everything In Between

12 tutorials beginner / intermediate

Loops are where Python programs do their real work -- processing data, transforming collections, retrying operations, and building results iteratively. Python gives you two core loop types (for and while) plus a set of control tools (break, continue, else clauses) that are more nuanced than they first appear.

This learning path starts with the basics of each loop type, moves into comparison and selection, then covers the control flow tools and common pitfalls that trip up developers at every level.

Tutorials marked with the cert badge include a final exam that awards a certificate of completion you can download and share.

secure coding

Writing Secure Python Loops

Loops are not security-neutral constructs. The same iteration patterns that make Python expressive can introduce vulnerabilities when they operate on untrusted input, unbounded data, or shared mutable state. The principles below apply across for loops, while loops, and comprehensions.

  • LIMIT Always bound iteration over external input. A loop that iterates until a condition from user-controlled data is satisfied is a denial-of-service risk. Set an explicit upper bound before the loop begins. For example, for item in islice(user_data, MAX_ITEMS) from itertools is a clean pattern that does not require you to trust the length of the input collection.
  • GUARD Validate before processing, not inside the loop body. It is tempting to filter or sanitize data mid-loop with a continue. That works, but it means malformed or adversarial values reach your loop body before being rejected. Where possible, sanitize the collection before iteration begins so the loop body only ever sees clean data.
  • AVOID Never construct shell commands or SQL strings inside a loop. Building a command or query from loop variables by string concatenation or f-string interpolation creates injection vulnerabilities at scale -- one bad value in the iterable means one injection payload executes. Use parameterized queries and subprocess with a list of arguments, not a shell string.
  • MUTATE Do not modify a collection while iterating over it. Mutating a list, dict, or set inside a loop that iterates the same object can cause skipped elements, duplicate processing, or in some patterns, infinite iteration. Create a copy to iterate over (for item in list(my_list)) and apply modifications to the original, or collect changes and apply them after the loop finishes.
  • TIMEOUT Give while loops an explicit escape that does not depend solely on external state. A while loop waiting on a network response, a file lock, or a queue signal can hang indefinitely if the expected state never arrives. Use a counter, a timeout via time.monotonic(), or a threading event with a deadline alongside your primary condition, so the loop cannot be stalled from outside the process.
  • LEAK Watch for sensitive data accumulation in loop buffers. Loops that accumulate results into a list, dict, or string variable across large datasets can hold credentials, PII, or session tokens in memory far longer than necessary. Process and discard sensitive items in-place where possible, rather than building a full result set before acting on it.
  • EXCEPT Handle exceptions inside loops explicitly. A bare except: that swallows all exceptions inside a loop is a security blind spot -- it can suppress evidence of injection attempts, malformed payloads, or permission errors. Catch specific exception types, log what you catch, and decide explicitly whether to continue, break, or re-raise.

Frequently Asked Questions

A for loop is designed for iterating over a known sequence or iterable -- a list, tuple, string, range, or any object that implements the iterator protocol. You use a for loop when you know the collection you want to traverse or when you want to iterate a specific number of times.

A while loop is designed for repeating a block of code as long as a condition evaluates to True. You use a while loop when the number of iterations is not known in advance and depends on something that changes during execution, such as user input, a network response, or an accumulating result.

Yes. Both for loops and while loops in Python support an else clause, which is a feature unique to Python among widely-used languages. The else block runs only if the loop completes normally -- that is, without being terminated by a break statement. If break is executed, the else block is skipped entirely.

This makes the else clause useful for search patterns: if you loop looking for a condition and use break when you find it, you can put the "not found" logic in the else block rather than tracking a flag variable through the loop.

An infinite loop occurs when a loop's termination condition is never reached. The most common causes are a while loop condition that is always True, a loop variable that is never updated inside the body, a break statement that is never triggered, or external state that the condition depends on but that never changes.

Prevention strategies include: ensuring the loop variable or condition state changes meaningfully on every iteration, adding a counter-based fallback that forces exit after a maximum number of iterations, using a timeout mechanism for loops waiting on external signals, and tracing through the logic manually to confirm every execution path eventually reaches a terminating condition.

No. Modifying a list while iterating over it with a for loop produces undefined behavior -- elements can be skipped, processed twice, or the loop can terminate earlier than expected. Python does not raise an error when this happens to lists, which makes the bug silent and hard to track down.

The correct pattern is to iterate over a copy of the list (for item in list(my_list):) while applying changes to the original, or to collect the items you want to remove and apply those changes after the loop finishes. For dicts, Python 3 will raise a RuntimeError if you change the size of a dict while iterating it, which at least makes the mistake visible.

The name is a play on words rooted in two sides of the same person. PythonCodeCrack is run by Kandi Brian, who holds an M.S. in Cybersecurity and Information Assurance and works as an active cybersecurity defender -- her daily tradecraft includes cybersecurity, backed by CompTIA Security+, CySA+, and PenTest+ certifications. The word "crack" nods to that security background, but that is the secondary meaning.

The primary meaning is about being hooked on Python itself. The term "crack addict" has long been used in pop culture as shorthand for someone who cannot put a thing down, and Python developers famously fall into that exact relationship with the language -- the clean syntax, the readability, the way idiomatic Pythonic code can express an algorithm in a handful of lines that would take a page in another language.

PythonCodeCrack is written for the people addicted to that elegance: developers who read PEPs for fun, who care about the difference between a list comprehension and a generator expression, and who want tutorials that respect the craft of writing good Python rather than just gluing snippets together.