Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 03 / Topic 5 of 12

while loop

while repeats as long as the condition is True. It is like "keep stirring while the tea is not ready". Make sure something inside the loop changes the condition, or it runs forever (an infinite loop; press Ctrl+C to stop it).

Real-world example: a lift counts down floors to the ground floor.

floor = 3
while floor > 0:
    print(f"Floor {floor}")
    floor -= 1          # move down one floor
print("Ground floor")
# Floor 3
# Floor 2
# Floor 1
# Ground floor

๐Ÿ” Going deeper: while True: with a break inside is a common pattern for menus and "keep asking until the input is valid". Python has no do ... while loop; this pattern is used instead.

Done here? The practice set for Part 3 โ€” 7 exercises with solutions โ€” is on the part page.

Search the guide