×

go · level 1 · unit 5 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.