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:
Tutorials
To further understand how an "if statement" works, try running the following tutorials:
Tutorial 2 - "Draw 2 hexagons"
Basic operators
The tutorials use a set of basic commands you might not have seen before.
- wall -> set background(colors -> red) - sets the background of the wall to a chosen colour.
- 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.
- 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
- 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.
- 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.