Python - Loops
What: Loops in Python are control structures used to repeat a block of code multiple times until a condition is met.
Why: To reduce redundancy, perform repeated tasks efficiently, and write DRY (Don't Repeat Yourself) code.
When: Use loops when you need to perform an action repeatedly, such as iterating over a list, performing calculations, or automating tasks.
1. for Loop
The for loop is used for iterating over a sequence (like a list, tuple, dictionary, set, or string).
2. while Loop
The while loop executes a block of code as long as the condition is true.
3. break Statement
break is used to exit the loop prematurely when a condition is met.
4. continue Statement
continue skips the current iteration and continues with the next one.
5. else with Loops
else block after loop executes if loop ends normally (not via break).
Pros
s- Efficient iteration
- Reduces redundancy
- Highly readable and concise
Cons
- Can lead to infinite loops if condition isn't updated properly
- May be overused where vectorized solutions (NumPy, pandas) are better
Use Python loops mindfully to write efficient and readable code.