DEV Community

sridhar n
sridhar n

Posted on

Python Day 11 – Writing Loops the "Micro to Macro" Way

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=' ')
# ...
Enter fullscreen mode Exit fullscreen mode

See the repeating part? print then +1. So:

no = 1              # initial value
while no <= 5:      # condition
    print(no, end=' ')
    no = no + 1     # increment
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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):

  1. Set count to 1.
  2. 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)