Decisions in programs — Computing, 7–10 years
Programs often need to choose between actions. A condition such as “if the door is open” lets a program respond to what it finds instead of doing exactly the same thing every time.
If this, then that
A decision in a program checks a condition and chooses an action. For example: if the light sensor says it is dark, switch on the lamp; otherwise, leave it off. This gives a program different paths through its instructions.
Why do programs choose?
The world does not always give a program the same situation. A game must react differently when a player wins or loses, and a robot must react differently when its path is blocked. Conditions solve this problem by connecting information to an appropriate action.
Example: a rain decision
Imagine a program helping you choose clothes. Step 1: check whether rain is forecast. Step 2: if rain is yes, choose a coat and boots. Step 3: if rain is no, choose a jacket and trainers. The program uses one question to select one of two sensible results.
The trap: forgetting the other case
People often write what should happen when a condition is true, but forget what happens when it is false. That is reasonable because we usually focus on the event we expect. A program still needs a safe choice, or it may do nothing confusing or keep an old action.
Where does it appear?
A lift checks which floor button was pressed, a thermostat checks whether a room is too cold, and a game checks whether a character touched a coin. These are real decisions based on information. The program does not guess; it follows a condition and a chosen response.
Keep exploring
Other languages
Loading MyLeoNes™…