Python Loops - Detailed Notes
1. Python Loops
Loops in Python allow for the repeated execution of a block of code. Python provides two main
types of loops: for loops and while loops. Each type has its use cases and functionalities.
2. for Loop
The for loop is used for iterating over a sequence (like a list, tuple, dictionary, set, or string). With
each iteration, the loop goes through an element in the sequence.
Syntax:
for variable in sequence:
# code block to be executed
Example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Key Concepts of for Loops
- Looping through a Range:
for i in range(5):
print(i)
Output:
- Looping with Step:
for i in range(0, 10, 2):
print(i)
Output:
- Looping with Else Clause:
for i in range(3):
print(i)
else:
print('Loop finished')
Output:
0
Loop finished
- Nested for Loops:
for i in range(3):
for j in range(2):
print(f'i: {i}, j: {j}')
Output:
Each combination of i and j
3. while Loop
A while loop continues to execute as long as a given condition is true. It is generally used when the
number of iterations is unknown and depends on a condition.
Syntax:
while condition:
# code block to be executed
Example:
count = 0
while count < 5:
print(count)
count += 1
Output:
0
Key Concepts of while Loops
- Infinite Loops:
while True:
print('Infinite loop')
break
- while Loop with Else Clause:
count = 0
while count < 3:
print(count)
count += 1
else:
print('Condition no longer true')
Output:
Condition no longer true
4. Control Statements in Loops
- break: Exits the loop immediately
for i in range(5):
if i == 3:
break
print(i)
Output:
- continue: Skips the current iteration and moves to the next
for i in range(5):
if i == 3:
continue
print(i)
Output:
- pass: Acts as a placeholder; does nothing but syntactically completes the block
for i in range(5):
if i == 3:
pass
print(i)
Output:
5. Common Use Cases of Loops
- Looping through Lists:
items = [1, 2, 3]
for item in items:
print(item)
- Looping through Dictionaries:
my_dict = {'a': 1, 'b': 2}
for key, value in my_dict.items():
print(f'{key}: {value}')
- Looping through a String:
text = 'hello'
for char in text:
print(char)
- Loop with Index:
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f'Index {index}: {fruit}')
Summary Table
| Loop Type | Use Case |
|----------------------|-----------------------------------|
| for | Known number of iterations |
| while | Unknown number of iterations |
| break | Exit loop immediately |
| continue | Skip current iteration |
| pass | Placeholder, does nothing |
| for with else | Executes if loop completes fully |
| while with else | Executes if loop completes fully |