Python – For and While Loops
In Python, loops are used to repeatedly execute a block of code. There are two main types of loops: for
loops and while
loops. Let’s explore each, including their variations and best practices.
for
Loops:
- Basic
for
Loop:- The basic
for
loop iterates over a sequence (e.g., a list, tuple, string, or range).
pythonfor item in sequence:
# Code to execute for each item
- The basic
range()
Function withfor
Loop:- The
range()
function generates a sequence of numbers that can be used with afor
loop.
pythonfor i in range(5):
# Code to execute for each iteration (0 to 4)
- The
enumerate()
Function:enumerate()
is used to iterate over both the indices and values of a sequence.
pythonfor index, value in enumerate(sequence):
# Code to execute for each index and value
zip()
Function:zip()
combines multiple sequences and iterates over them simultaneously.
pythonfor item1, item2 in zip(sequence1, sequence2):
# Code to execute for each pair of items
while
Loops:
- Basic
while
Loop:- The basic
while
loop continues executing as long as a specified condition isTrue
.
pythonwhile condition:
# Code to execute while the condition is True
- The basic
Loop Control Statements:
break
Statement:break
is used to exit a loop prematurely.
pythonfor item in sequence:
if condition:
break
continue
Statement:continue
skips the rest of the loop’s code and moves to the next iteration.
pythonfor item in sequence:
if condition:
continue
# Code to execute for non-matching items
Dos and Don’ts:
Dos:
- Use Descriptive Variable Names: Choose meaningful variable names to enhance code readability.
- Keep Code Inside the Loop Concise: Avoid excessive nesting and keep the code inside the loop focused.
- Use
enumerate()
andzip()
for Multiple Sequences: Simplify code when iterating over multiple sequences.
Don’ts:
- Modify the Sequence Inside a
for
Loop: Avoid modifying the sequence being iterated over; it can lead to unexpected behavior. - Use
while True
Without Proper Exit Conditions: Ensure there is a condition to exit awhile True
loop to prevent infinite loops.
Best Use Cases:
for
Loops: Ideal for iterating over sequences, such as lists, tuples, and strings.while
Loops: Useful when the number of iterations is unknown and depends on a condition.break
andcontinue
: Effective for controlling loop flow and handling specific conditions during iteration.
Â
Loop Cheat Sheet:
This cheat sheet provides an overview of ‘For’ loops, ‘While’ loops, and related concepts in Python, along with dos, don’ts, and best practices for their usage.
Loop Type | Example | Pros | Cons | Best Usage | Alternatives | |||
---|---|---|---|---|---|---|---|---|
`for` Loop | ```python for item in sequence: # Code``` | - Iterates over sequences | - Limited to predefined sequences | Iterating over lists, tuples, strings, and ranges | `map()` and list comprehensions | |||
`range()` with `for` Loop | ```python for i in range(5): # Code``` | - Generates a sequence of numbers | - Requires converting to a list for Python 2 | Iterating a specific number of times | `xrange()` in Python 2 | |||
`enumerate()` with `for` Loop | ```python for index, value in enumerate(sequence): # Code``` | - Iterates with both indices and values | - Slightly more overhead than a basic `for` loop | Simultaneously accessing index and value in a loop | Nested `for` loops for indices and values | |||
`zip()` with `for` Loop | ```python for item1, item2 in zip(sequence1, sequence2): # Code``` | - Iterates over multiple sequences | - Stops when the shortest sequence is exhausted | Simultaneously iterating over multiple sequences | Nested `for` loops for each sequence | |||
`while` Loop | ```python while condition: # Code``` | - Continues while a condition is True | - Requires explicit condition for termination | Iterating when the number of iterations is unknown | `for` loop with a known number of iterations | |||
`break` Statement | ```python for item in sequence: if condition: break``` | - Exits the loop prematurely | - Can lead to unexpected termination | Terminating a loop based on a specific condition | `return` statement | |||
`continue` Statement | ```python for item in sequence: if condition: continue # Code``` | - Skips the rest of the loop's code | - Can lead to code duplication if not used carefully | Skipping specific iterations in a loop | Adjusting loop conditions |