This guide will help you understand how "if" statements work. Programs without conditional statements will usually run the same way every time. This is why using “if” statements may allow the flow of the program to be changed.


Basic syntax

if condition then

| body

else body end if


Basic operators

The basic operators that can be used in an "if statement" are:

  • > greater than (e.g. 14 > 4 is TRUE)
  • < less than (e.g 0 < 5 is TRUE)
  • >= greater than or equal (e.g. 7 >= 7 is TRUE)
  • <= less than or equal (e.g. 3 <= 4 is TRUE)
  • == equal to (e.g. 11 == 11 is TRUE)
  • != not equal to (e.g. 5 != 4 is TRUE)


    Tutorials

    To further understand how an "if statement" works, try running the following tutorials:

  • Tutorial 1 - "Change colour of screen"

  • Tutorial 2 - "Draw 2 hexagons"


    Basic operators

    The tutorials use a set of basic commands you might not have seen before.

    1. wall -> set background(colors -> red) - sets the background of the wall to a chosen colour.
    2. The turtle library: It comes with some basic commands, such as move forward, turn right/left.
      • turtle -> forward(x) - Makes the turtle move forward over the distance x.
      • turtle -> left turn(x) - Makes the turtle turn to the left by x degrees.

    Exercises

    Now try it yourself.

    1. Change the turtle script so that it will draw 2 heptagons instead of hexagons.

      Useful tips: think how you can change the for loop and the if statement depending on the number of sides and the angle

    2. Write a script so that the user can input a number and if the number entered is less than 5 change the background to green, if it is between 5 and 10 change it to red and to blue otherwise.
    3. Create a script using For Loop and If Statement. For numbers from 0 to 100, we want to print out the numbers which contain ‘6’. Calculate the sum of them and print out the sum.


    Don't stop here! Experiment with the commands you have learned and create scripts of your own.



    PREVIOUS LESSON

    NEXT LESSON

    BACK TO INDEX