beginnerControl Flow

Loops (For & While)

Iterate over sequences and repeat code with for and while loops.

01For Loop

Iterate over any iterable (list, string, range, etc.).

Python
1fruits = ["apple", "banana", "cherry"]
2
3for fruit in fruits:
4 print(fruit)
Output
apple
banana
cherry

02Range Function

Generate a sequence of numbers for looping.

Python
1for i in range(5):
2 print(i, end=" ")
3print()
4
5for i in range(2, 8, 2):
6 print(i, end=" ")
Output
0 1 2 3 4 
2 4 6

03While Loop

Repeat while a condition remains True.

Python
1count = 0
2while count < 5:
3 print(count, end=" ")
4 count += 1
Output
0 1 2 3 4

04Break, Continue & Else

Control loop execution with break (exit), continue (skip), and else (runs if no break).

Python
1for i in range(10):
2 if i == 3:
3 continue # skip 3
4 if i == 7:
5 break # stop at 7
6 print(i, end=" ")
7else:
8 print("Done") # won't run because of break
Output
0 1 2 4 5 6