1. What are Loops?
- Loops are used to repeatedly execute a block of code.
- They are essential for automating repetitive tasks and iterating over sequences like lists, tuples, strings, etc.
- Python supports two types of loops:
forloopswhileloops
2. for Loop
- The
forloop is used to iterate over a sequence (e.g., list, tuple, string, range) or other iterable objects. - Syntax:
Using range() in for Loops
- The
range()function generates a sequence of numbers. - It is commonly used to iterate a specific number of times.
3. while Loop
- The
whileloop repeats a block of code as long as a condition isTrue. - Syntax:
4. Loop Control Statements
- These statements alter the flow of loops:
break: Exits the loop immediately.continue: Skips the rest of the code in the current iteration and moves to the next iteration.pass: A placeholder for future code (does nothing).
-
break:Output: -
continue:Output: -
pass:Output:
5. Nested Loops
- A loop inside another loop is called a nested loop.
- Commonly used for working with multi-dimensional data structures.
6. Iterating Over Sequences
- Loops can iterate over various sequences like lists, tuples, strings, dictionaries, etc.
-
List:
-
String:
-
Dictionary:
7. Additional Examples
-
forLoop: -
whileLoop: -
Nested Loops:
-
Loop Control:
8. Best Practices
- Use meaningful variable names for iterators (e.g.,
nameinstead ofx). - Avoid infinite loops in
whileloops by ensuring the condition eventually becomesFalse. - Use
breakandcontinuesparingly to keep the code readable. - Use list comprehensions for simple loops that create lists.