go · level 1 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A for with only a condition runs while it is true.
Sometimes you do not know how many rounds you need. You keep going while something is true, like stirring while the soup is lumpy. In Go, a for with only a condition works as a .
for energy > 0 { checks before every round. true? Run the block, then check again. false? Stop and move on to the next line.
Something inside the block must change, or the condition stays true for ever. That is an , and the program never stops. Here, energy = energy - 1 makes sure it ends.
package main
import "fmt"
func main() {
energy := 3
for energy > 0 {
fmt.Println("Running! Energy:", energy)
energy = energy - 1
}
fmt.Println("Time for a nap.")
} If a program seems stuck, look for a loop whose condition can never become false.
guess first
Double it until it is big. What is the end result?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
coins := 1
for coins < 20 {
coins = coins * 2
}
fmt.Println(coins)
}
your turn
Your turn. Save up for a bike.
Type the price of a bike in the first blank, then how much you save each week in the second. Make the weekly amount more than 0, or the loop never ends!
output
press run to see what happens
fix it
Nobody got a biscuit. Can you fix it?
output
press run to see what happens
- The loop never runs at all. Is
3 < 0true or false? - The loop should keep going while there are biscuits left, which means more than 0.
- Change
<to>on line 5, then press run.
nailed it
your loops know when to stop. :D
for condition {repeats while the condition istrue.- Something inside the loop must change.
- A loop that never ends is an infinite loop.
new words in your collection
- while loop
- infinite loop
This lesson isn’t saved. A free account remembers every lesson you finish.