Core Skills

Chapter 9 of 18

Chapter 9: Make Scripts Decide and Repeat

This chapter is about control structures, which are the three ways code can flow: in order, by choice, or by repetition. You will learn sequence, which is simply one step after another, selection, which is an if choice with branches, and iteration, which is a loop that repeats a block. That matters because every script you will ever write is built from these three ideas, and once you see them clearly, longer scripts stop looking scary. You will practise choosing the right branch order and making sure every loop can end. After this chapter, you will be able to write if, elseif, and else chains, write for, while, and foreach loops, and explain in plain words why a script took the path it took.

2 lessons 3 learning objectives

Topics at a glance: Sequence and selection: if, elseif, else, Iteration: for, while, and foreach.

Where this chapter fits

This chapter comes after Chapter 8: Build Your Own Commands in the journey, so ideas from that chapter will feel familiar here.

After this chapter comes Chapter 10: Run Commands on Other Computers.

Learning objectives

By the end of this chapter, you will be able to:

  • Explain sequence, selection, and iteration
  • Write if, elseif, and else correctly
  • Write for, while, and foreach loops correctly

Lessons in this chapter

Work through the lessons in order. Each lesson page has explanations, examples, common mistakes, and a knowledge check.

  1. Lesson 1: Sequence and selection: if, elseif, else

    Sequence is the default: run one step, then the next. Selection adds a choice: run a block only when a condition is true, or choose between branches.

    3 things to learn in this lesson

  2. Lesson 2: Iteration: for, while, and foreach

    Iteration repeats a block. For repeats a counted number of times, while repeats while a condition holds, and foreach repeats once per item in a collection.

    3 things to learn in this lesson