Loops
Loops
In Python, a `for` loop is used to iterate over a sequence (such as a list, tuple, string, or range) and
execute a code block for each item in the sequence. Here's the basic syntax:
# code to be executed
Key Points:
1. `variable`: A temporary variable that takes the current item's value in the sequence during each
iteration.
2. `sequence`: The collection or iterable you're looping through (like a list, string, or range).
3. Indentation: The code block inside the loop is indented to indicate that it belongs to the loop.
print(fruit)
Output:
apple
banana
cherry
print(i)
Output:
1
2
print(letter)
Output:
`else` Clause:
You can use an optional `else` block with a `for` loop. The `else` part is executed when the loop
finishes iterating over the sequence without hitting a `break`.
for i in range(3):
print(i)
else:
print("Finished looping!")
Output:
0
Finished looping!
if num == 3:
break
print(num)
Output:
if num == 3:
continue
print(num)
Output:
0
While Loops
A while loop in Python allows you to repeatedly execute a code block as long as a certain condition is
true. It is useful when the number of iterations is not predetermined and depends on a condition
evaluated at runtime.
Syntax:
while condition:
The condition is a boolean expression that is evaluated before each iteration of the loop.
If the condition becomes False, the loop stops, and the program continues with the next
statement after the loop.
Example:
count = 0
print(count)
count += 1
Explanation:
The condition count < 5 is checked. Since it's true, the block inside the loop is executed.
The loop continues until count becomes 5, after which the condition count < 5 evaluates to
False, and the loop stops.
1. Infinite Loops: A while loop can potentially run forever if the condition never becomes False.
This is known as an infinite loop.
while True:
2. Break Statement: The break statement is used to exit the loop prematurely, even if the
condition is still true.
count = 0
print(count)
if count == 5:
count += 1
3. Continue Statement: The continue statement is used to skip the remaining code in the
current iteration and proceed with the next iteration of the loop.
count = 0
count += 1
if count == 3:
print(count)
4. Else Block: An else block can be attached to a while loop, which executes when the loop
condition becomes False.
count = 0
print(count)
count += 1
else:
User Input Validation: Keep asking for valid input until the user enters the correct value.
Background Tasks: Continuously check for some background process until a condition is met.
Repetition Until a Condition: For tasks that need to repeat until a certain condition is
achieved.
Common Pitfalls:
1. Infinite Loop by Accident: If you forget to update the condition within the loop, it may result
in an infinite loop.
x = 10
while x > 5:
print(x)
2. Logical Errors in Conditions: Incorrect conditions can lead to loops that either don’t execute
at all or exit prematurely.
The while loop is powerful when you need flexibility in determining how many times to iterate. If you
know beforehand how many times to loop, a for loop is often preferred.
FOR vs WHILE
Feature For Loop While Loop
Use case They are used when the number They are used when the number of
of iterations is known or finite iterations is not known in advance
(iterating over sequences like and depends on a condition.
lists, strings, etc.).
Syntax for variable in sequence: while condition:
Iterates Over a sequence of items (like As long as the condition remains
lists, tuples, strings, ranges). True.
Condition evaluation Implicitly based on the sequence Explicitly evaluates a condition
(no explicit condition needed). before each iteration.
Termination Terminates after going through all Terminates when the condition
items in the sequence. becomes False.
Infinite loops Typically, doesn't result in an Can result in infinite loops if the
infinite loop unless intentionally condition never becomes False.
written as such.
Readability Easier to read and more compact Requires more careful handling for
for known iterations. conditional and indefinite loops.
Break and continue Supports `break` and `continue` Supports `break` and `continue` to
to control loop flow. control loop flow.
Else block Can have an `else` block that Can also have an `else` block that
executes after the loop ends executes if the loop ends naturally.
naturally.
Performance Ideal for iterating over collections Ideal for loops that need to run
efficiently. based on conditions rather than
collections.