Loops and conditions
Two big ideas in coding, repeating instructions with loops and making decisions with conditions, shown in Scratch.
Two big ideas in coding: repeating things, and making decisions. Imagine telling a robot to walk ten steps by writing walk one step, ten times. Boring! A loop repeats instructions for you. In Scratch, the repeat block runs everything inside it again and again.
A loop
Let's build one. When green flag clicked. Repeat ten. Everything inside this block happens ten times. Move ten steps. And turn thirty six degrees. Ten turns of thirty six degrees make a full circle, so the sprite walks around in a ring.
Two kinds of loop
Repeat runs the blocks inside a set number of times, like ten. Forever keeps going until you press the stop button. Games use forever loops all the time. The second big idea is a condition, which lets a program make decisions. If something is true, do one thing. Otherwise, do something else. You use conditions every day. If it's raining, take an umbrella.
A condition inside a loop
Here's a condition inside a loop. When green flag clicked. Forever, keep checking. If the sprite is touching the edge of the screen, then. Say ouch. The forever loop keeps asking, so the sprite says ouch every time it reaches the edge.
New word: Bug
When a program doesn't do what you expected, it has a bug, a mistake in the code. Finding and fixing bugs is called debugging. Every programmer does it, all the time. Check your blocks one by one, and test again.
Quick check
Quick check. You want a sprite to jump five times. Which block helps? Repeat five. Put the jump blocks inside it. Options: repeat (5); if then; say Hello; stop all.
Recap
Loops repeat instructions. Repeat runs a set number of times, and forever keeps going. Conditions use if to make decisions. And loops and conditions often work together.
Key points
- A loop repeats instructions. "repeat (10)" runs a set number of times; "forever" runs until you stop it.
- A condition makes a decision. "If something is true, then do this."
- Programs often put conditions inside forever loops, so they keep checking.
- 10 turns of 36 degrees make a full circle (360 degrees).
Try it: Loop or condition?
Decide which coding idea fits each task.