1. Display the Same Number Five Times
Problem: A teacher asks five students to stand in a line. Each student wears a badge with the number 1. Display the badge numbers from left to right.
Without a loop
print(1, end=' ') print(1, end=' ') print(1, end=' ') print(1, end=' ') print(1, end=' ') With a while loop
count = 1 while count <= 5: print(1, end=' ') count = count + 1 Output: 1 1 1 1 1 Instead of writing print(1) five times, we use a loop to repeat the action.
Display Roll Numbers from 1 to 5
Problem: Five students enter the classroom one after another. The first student gets roll number 1, the second gets 2, and so on. Display the assigned roll numbers.
Without a loop
print(1, end=' ') print(2, end=' ') print(3, end=' ') print(4, end=' ') print(5, end=' ') Understanding the repeated action
no = 1
print(no, end=' ')
no = no + 1
print(no, end=' ')
no = no + 1
print(no, end=' ')
no = no + 1
print(no, end=' ')
no = no + 1
print(no, end=' ')
Using a while loop
no = 1 while no <= 5: print(no, end=' ') no = no + 1 Output: 1 2 3 4 5 This is called Micro to Macro: first understand the repeated steps, then convert them into a loop.
Display the First Five Even Positions
Problem: A coach asks students to stand only at even-numbered positions in a queue. Displlay the first five positions.
position = 2 while position <= 10: print(position, end=' ') position = position + 2 Output: 2 4 6 8 10 Here, we increase the position by 2 instead of 1.
Lift Stops at Every Third Floor
Problem: A newly constructed building has a special lift that does not stop on every floor. It stops only at every third floor. A person enters the lift at the ground floor and presses the "Up" button five times. Display the floors where the lift stops.
button = 1 floor = 3 while button <= 5: print(floor) button = button + 1 floor = floor + 3 Output: 3 6 9 12 15 Here:
- button counts how many times the button is pressed.
- floor stores the next stopping floor.
- Each time, the floor increases by 3.
Rocket Countdown Using Even Numbers
Problem: A rocket launches with a countdown using only even numbers from 10. Display the countdown.
count_down = 10 while count_down >= 0: print(count_down, end=' ') count_down = count_down - 2 Output: 10 8 6 4 2 0 Here, we use decrement instead of increment because the countdown moves backwards.
Key Takeaways
- A loop is used to repeat an action.
- while executes as long as its condition is True.
- Initialization sets the starting value.
- The condition decides when the loop stops.
- Increment increases a value.
- Decrement decreases a value.
- Always update the loop variable to avoid an infinite loop.
Remember: Don't try to think about the entire output at once. Understand the next step, dry-run the program, and gradually build the complete logic.