If Statements

Cymraeg

THIS PAGE IS UNDERGOING CHANGES - PLEASE RETURN SHORTLY

If Statements

This page aims to explain how if statements work in programming, with examples and exercises.

What is an if statement?

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?

  1. 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.

  2. 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.

  3. 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.

The circuit for this example

Makecode for Micro:Bit

The forever block contains an 'if light level is less than or equal to 70 then' block which then contains a 'digital write pin 0 to 1' block.

Tinkercad Blocks

The forever block contains an 'if light level is less than or equal to 70 then' block which then contains a 'digital write pin P0 to HIGH' block.

Javascript

                   
if (input.lightLevel() <= 70) {
  pins.digitalWritePin(DigitalPin.P0, 1)
}
          
        

Python

          
if input.light_Level() <= 70:
  pins.digital_write_pin(DigitalPin.P0, 1)