Repeat while a condition holds
Repeat while a condition holds
Go uses for condition { ... } for a condition-only loop; there is no separate while keyword. The Boolean condition is tested before every iteration. If it is false at the start, the body runs zero times.
package main
import "fmt"
func main() { balance := 12 for balance >= 5 { balance -= 5 fmt.Println(balance) }}Each purchase subtracts five units. After the second purchase, the remaining balance is 2 and the condition is false. The changing balance is the state that controls termination.
Handle a condition that starts false
package main
import "fmt"
func main() { attempts := 0 for attempts > 0 { fmt.Println("retry") attempts-- } fmt.Println("finished")}No retry is printed. If the condition starts true and the body never changes the relevant state, the loop may never terminate. Go also permits for { ... } with no condition; a later break or return can end it. Do not run an unbounded loop as a practice example.
Try it locally
Start with pages := 7. While pages is positive, print its current value then subtract 3. Expected lines: 7, 4, 1.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Loops 02: Repeat while a condition holds
Check the lesson objective before moving on.
What happens if the condition is false initially?
Which change helps ensure a positive countdown ends?