Python Loops Notes
Python Loops 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
Syntax:
Example:
print(fruit)
Output:
apple
banana
cherry
for i in range(5):
print(i)
Output:
print(i)
Output:
for i in range(3):
print(i)
else:
print('Loop finished')
Output:
0
Loop finished
for i in range(3):
for j in range(2):
Output:
3. while Loop
A while loop continues to execute as long as a given condition is true. It is generally used when the
Syntax:
while condition:
Example:
count = 0
print(count)
count += 1
Output:
0
- Infinite Loops:
while True:
print('Infinite loop')
break
count = 0
print(count)
count += 1
else:
Output:
for i in range(5):
if i == 3:
break
print(i)
Output:
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:
items = [1, 2, 3]
print(item)
print(f'{key}: {value}')
text = 'hello'
Summary Table
|----------------------|-----------------------------------|