Loading lesson...
Repeating actions efficiently
Repeating actions efficiently
Topics covered: Iterating with for Loops, range() Function, Loops with while, Using break and continue, Loop Variable Scope
A for loop repeats a block of code once for each item in a sequence. Without one, processing fifty files means writing fifty nearly-identical blocks of code. A loop collapses all of that into three lines. Basic for Loop Syntax Looping Over Strings Strings are sequences of characters, so you can loop over them character by character: Each character in the string becomes the loop variable in turn. This is useful for analyzing text character by character. Accumulating Results A common pattern is to
range() with One Argument range() with Two Arguments range() with Three Args range() for Index Access Sequences from range() Repeating Actions N Times Sometimes you just need to repeat an action a specific number of times without caring about the loop variable. By convention, you can use an underscore for variables you do not intend to use:
Basic while Syntax The loop checks the condition, executes the body if True, then checks again. When count reaches 5, the condition becomes False and the loop ends. Here is the execution model step by step: Comparing while and for Choose the right loop type based on your situation: When deciding which loop type to use, keep these practical rules in mind. They cover the most common scenarios you will encounter in real code. Common while Patterns Here are typical use cases for while loops: Avoidin
The break Statement The continue Statement break vs continue Understanding the difference is crucial: break and continue in while These statements work the same way in while loops: Combining break with Flags Sometimes you need to know whether a loop exited normally or via break. A flag variable can track this distinction: The flag variable starts False and becomes True only if the target is found. After the loop, you check the flag to determine the outcome. This pattern is useful when you need d
Loop Variables Persist Empty Loops: Undefined Vars If a loop never executes (empty sequence), the loop variable is never assigned: Understanding how loop variables behave in Python helps avoid common bugs, especially when accessing them after the loop ends: Nested Loop Scope Each loop has its own variable, but inner loops can access outer loop variables: Common Mistakes These are frequent errors when writing loops: Loops are essential for automating repetitive tasks and processing collections of