Python Loops
Loops in Python are used to execute a block of code repeatedly based on a condition or for iterating over a sequence. They are essential for performing repetitive tasks efficiently.
1. for
Loop
The for
loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) or other iterable objects.
Basic Syntax:
Example:
Iterating over a List
Output:
Explanation:
- The
for
loop iterates over each item in thefruits
list and prints it.
Iterating over a Range
Output:
Explanation:
- The
range(5)
generates numbers from0
to4
, and the loop prints each number.
Iterating over a Dictionary
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
for key, value in person.items():
print(key, value)
Output:
Explanation:
- The
items()
method returns key-value pairs of the dictionary, which are iterated and printed.
2. while
Loop
The while
loop in Python continues to execute a block of code as long as a specified condition is True
.
Basic Syntax:
Example:
Basic while
Loop
Output:
Explanation:
- The loop continues as long as
count
is less than5
. Thecount
variable is incremented in each iteration.
while
Loop with break
Output:
Explanation:
- The
while True
loop runs indefinitely but is terminated by thebreak
statement whencount
reaches5
.
while
Loop with continue
Output:
Explanation:
- The
continue
statement skips the rest of the code in the loop for even values ofcount
, so only odd numbers are printed.
3. Nested Loops
Loops can be nested within each other to perform more complex iterations.
Example:
Nested for
Loops
Output:
Explanation:
- The outer loop runs 3 times, and for each iteration of the outer loop, the inner loop runs 3 times.
4. Loop Control Statements
4.1. break
The break
statement terminates the loop prematurely.
Example:
Output:
Explanation:
- The loop breaks when
i
equals5
, so only numbers from0
to4
are printed.
4.2. continue
The continue
statement skips the current iteration and moves to the next iteration.
Example:
Output:
Explanation:
- Even numbers are skipped due to the
continue
statement, so only odd numbers are printed.
4.3. pass
The pass
statement is a placeholder that does nothing and is used when a statement is syntactically required but no action is needed.
Example:
Explanation:
- The
pass
statement does nothing; the loop executes without performing any actions.
Conclusion
Loops in Python are powerful constructs for executing repetitive tasks and iterating over sequences. By understanding the for
and while
loops, as well as loop control statements like break
, continue
, and pass
, you can write efficient and effective code for various programming tasks.