If, for and switch

Knowledge Videos

Short animated explainers, organised by subject.

If, for and switch

Decisions and loops in Go: if and else without brackets, the three shapes of for (counted, condition, forever), and switch, next to the same ideas in Scratch.

Try it

Transcript

Decisions look familiar. An if checks a condition, and else handles the other case. In Go you do not put brackets around the condition, but the curly braces are always required.

Go has only one loop: for. It has three shapes. A counted loop with a start, a test and a step. A loop with just a test, like a while loop in other languages. And a loop that goes on forever, until you break out of it.

A switch picks one case. It is a tidy way to write many if and else checks, and Go stops at the first case that matches.

Compare with Scratch. Repeat ten is a for loop. The if and else blocks are if and else. The same road signs, written as text.

Remember: if and else decide, for is the only loop with three shapes, and switch picks one case.

More in this series