THIS PAGE IS UNDERGOING CHANGES - PLEASE RETURN SHORTLY
This page aims to explain how if statements work in programming, with examples and exercises.
When we run programs, we may not always want them to do exactly the same thing each time. Instead we might want them to be able to change their behaviour based on some conditions. This can be done with an if-statement.
As with other programming terms, it is based on written/spoken language. Here is a sentence using the same framework as an if statement.
If it is dark then turn on a light.
The above starts with the word if, has a condition of being dark, and then an action of turning on a light.
If it isn't dark we ignore the instruction. Same for a program - it will only follow an if instruction if the condition, in this case being dark, is true.
Now, how would we convert this sentence to a computer program?
You will need to have a way of measuring brightness: For this example we shall use a light sensor to provide a light level value.
What value you will use to indicate it is dark: In this case we shall say that any value less than or equal to 70 is dark enough to need a light.
The instruction for turning on a light: We shall have a lightbulb connected to pin 0.
Let us see how we could program a Micro:Bit connected to a LED on pin 0 with this if statement as shown in the below circuit. We shall use any light sensor value less than 70 as dark.
Makecode for Micro:Bit
Tinkercad Blocks
Javascript
if (input.lightLevel() <= 70) {
pins.digitalWritePin(DigitalPin.P0, 1)
}
Python
if input.light_Level() <= 70:
pins.digital_write_pin(DigitalPin.P0, 1)