Loops in Python are like repeating instructions in your code, saving you from writing the same lines over and over. They’re perfect for tasks like going through a list of items or counting until a goal is reached. Below, we’ll cover the main types in simple terms, with easy examples you can try yourself.
For Loop
The For Loop is used when you have a specific list of items or a set number of steps you want to complete. It’s like a delivery driver who has five packages; they will stop at each house on their route one by one until the truck is empty.
When to use it: When you know exactly how many times you need to repeat something or when you’re moving through a collection (like a list of names).
# Printing a simple greeting for every friend in a list friends= ["Alice", "Bob", "Charlie"] fornameinfriends: print("Hello, "+name)
While Loop
A While Loop keeps running as long as a specific rule or condition stays true. It’s like a vacuum cleaner that stays turned on as long as the power switch is in the “On” position; the moment you flip it to “Off”, the loop stops immediately.
When to use it: When you don’t know exactly how many times you’ll need to repeat the task, but you know what condition should make it stop.
# Counting down until the battery runs out battery=3
whilebattery>0: print("Phone is on...") battery=battery-1# Reducing battery by 1 each time print("Phone shut down.")
Nested Loops
A Nested Loop is simply a loop placed inside another loop. Think of it like a clock: the “hour” hand moves once (the outer loop), but before it can move again, the “minute” hand must go all the way around 60 times (the inner loop).
When to use it: When you have complex data, like a grid of numbers or a schedule with multiple days and multiple tasks per day.
# Matching every shirt color with every pant color shirts= ["Red", "Blue"] pants= ["Jeans", "Slacks"]
forsinshirts: forpinpants: print(s+" shirt with "+p)