Programming Basics
Loops (for & while)
The idea, in plain English
A loop tells the computer 'do this again' without typing the same instruction over and over. Use a 'for' loop when you know how many times to repeat, like counting to 5. Use a 'while' loop when you want to keep going UNTIL something becomes true, like pouring water until the cup is full — however many pours that takes.
How it works
- 1A `for` loop sets a counter, says how far to count, and says how much to add each time. It then repeats its body once per count.
- 2A `while` loop checks a condition before every repeat. As long as it's true, the body runs again.
- 3Every loop needs something that eventually stops it. The counter must run out, or the condition must become false. Otherwise the loop repeats forever.
When you'd use it
Use a loop anytime you need to repeat an action. Use `for` when you know the number of times to repeat, and `while` when you repeat until a condition changes. Examples: going through every item in a list, retrying until something succeeds, or counting down to zero.
Common beginner mistakes
- Forgetting to change the thing the loop checks, like forgetting to lower the countdown. This makes the loop run forever — called an 'infinite loop'.
- Off-by-one mistakes. The loop runs one time too many or too few, because of how the start and end points are counted.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Sum 1 to 5: 15
Countdown: 3
Countdown: 2
Countdown: 1
Liftoff!Not sure this is the right topic? See the learning paths → or where this leads →