Today was all practice. The method: write the repeated steps out by hand first, spot the pattern, then turn it into a loop.
Problem 1: Roll numbers 1 to 5
The micro version first:
no = 1
print(no, end=' ')
no = no + 1
print(no, end=' ')
no = no + 1
print(no, end=' ')
# ...
See the repeating part? print then +1. So:
no = 1 # initial value
while no <= 5: # condition
print(no, end=' ')
no = no + 1 # increment
Output: 1 2 3 4 5
Every loop has these 3 parts: initial value, condition, increment/decrement.
Problem 2: Even positions in a queue
position = 2
while position <= 10:
print(position, end=' ')
position = position + 2
Output: 2 4 6 8 10
Problem 3: The lift that stops every 3rd floor
A person presses "Up" 5 times, and the lift only stops at every third floor.
button = 1
floor = 3
while button <= 5:
print(floor, end=' ')
button = button + 1
floor = floor + 3
Output: 3 6 9 12 15
Or even simpler, without a separate floor variable:
button = 1
while button <= 5:
print(button * 3, end=' ')
button = button + 1
Fun fact: after the loop ends, button is 6, not 5. That's the value that made the condition false.
Problem 4: Rocket countdown (even numbers)
count_down = 10
while count_down >= 0:
print(count_down, end=' ')
count_down = count_down - 2
Output: 10 8 6 4 2 0
Writing the algorithm in words
The trainer wanted us to write steps in plain language (we did it in Tamil and English):
- Set count to 1.
- While count ≤ 5:
- print 1
- increase count by 1
If you can explain it in your own language, the code is the easy part.
Top comments (0)