Python Loops - Handwritten Style Notes
1. while Loop
Used when number of repetitions is unknown.
Syntax:
n = 0
while n < 5:
print('Hello', n)
n += 1
Make sure the condition changes to avoid infinite loop.
2. for Loop with range()
Used when the number of repetitions is known.
Syntax:
for i in range(1, 6):
print(i * '*')
You can also use step:
for i in range(0, 11, 2):
print(i)
3. Looping through a List
fruits = ['Apple', 'Banana', 'Orange']
for item in fruits:
print(item)
4. break, continue, pass
break - Exit loop completely
continue - Skip current iteration
pass - Placeholder, does nothing
Example:
for i in range(10, 51):
if i == 25:
break
print(i)
5. Pattern Printing
Python Loops - Handwritten Style Notes
Forward pattern:
for i in range(1, 6):
print(i * '*')
Reverse pattern:
for i in range(5, 0, -1):
print(i * '*')
6. List Comprehension
Short way to create lists:
print([i for i in range(1, 11)])
7. Nested Loops
Used in tables and pattern problems.
Example:
for i in range(1, 11):
for j in range(1, 11):
print(f'{i} x {j} = {i*j}')