blog.dopana

Back

Welcome back! 🚀 Today, we are going to learn how to make our Python robot do boring chores over and over again without ever complaining or getting tired.

Imagine your teacher asks you to write “I will not eat cookies in class” 100 times on the board. Your hand would hurt! But for our Python robot, writing it 100 times takes less than a millisecond.

To do this, we use Loops!

What is a Loop? (The Roller Coaster track)#

A loop is like a circular roller coaster track. The train keeps going around and around the circle until a condition says it’s time to stop.

graph TD
    Start([Start Loop]) --> Check{Is count < 5?}
    Check -- Yes --> Action["Print 'Loop-de-loop!' 🎡"]
    Action --> Add["Add 1 to count"]
    Add --> Check
    Check -- No --> End([Exit Loop])

If we don’t tell the loop when to stop, it will go on forever. That is called an infinite loop, and it makes the robot spin out of control!

1. The Counting Loop (for Loop)#

If you know exactly how many times you want the robot to repeat something, you use a for loop.

Let’s tell the robot to print a message 5 times:

for i in range(5):
    print("Loop-de-loop! 🎡")
python

How it works#

  • range(5) is like a list of 5 numbers: 0, 1, 2, 3, 4.
  • i is a temporary box that holds the current number.
  • Every time the loop runs, i grabs the next number, prints the text, and goes back to the start.
  • Don’t forget the colon : and the 4 spaces of indentation for the code inside the loop!

2. The Condition Loop (while Loop)#

What if you don’t know exactly how many loops you need, but you want to repeat something until a condition changes? You use a while loop.

For example, imagine our robot is running, and each step uses up 1 point of energy:

energy = 3

while energy > 0:
    print("Robot takes a step! 🏃")
    energy = energy - 1  # Using up 1 energy point
    
print("Out of energy! Robot rests. 💤")
python
graph TD
    A[Energy = 3] --> B{Is Energy > 0?}
    B -- Yes --> C["Print 'Robot takes a step!'"]
    C --> D[Energy = Energy - 1]
    D --> B
    B -- No --> E["Print 'Out of energy!'"]

The robot checks if energy > 0 is True. Since it is 3, it takes a step, reduces energy to 2, and loops. It repeats this until energy is 0. Then, the question becomes False, and the robot exits the loop!

Try It Yourself! 🎮#

Open your Python editor and try these tasks:

  1. Count to 10: Use a for loop and print(i) to make the robot count. (Note: range(10) starts at 0. Can you figure out how to make it print 1 to 10? Hint: print i + 1!)
  2. The Volcano Escape: Set a variable volcano_distance = 5. Write a while loop that prints "Running away! 🌋" and reduces the distance by 1 until it reaches 0.

Next time, we will learn how to pack our code into neat custom buttons called Functions so we can reuse them anytime we want. See you then!

References#