How do programs flow, and how do we control that flow?
This page assumes you have completed the variables lesson.
With the basic flow control mechanisms introduced here, we can decide which path our program will take. Computers aren’t very smart and everything needs to be laid out, including the flow of our program. Can you imagine how complex a flow control could get when you have to think and program for every possible scenario?
The if statement should be easy to understand. It checks if a condition is true to run a piece of code. For example, we want to print “Too hot” if the temperature (t) is more than 40 degrees Celsius.
t = 99 if t > 40 Print("Too Hot") End
Change t to 30 and try the code again.
The else statement works hand in hand with the if statement. It is there to indicate the opposite of the if statement.
t = 30 if t > 40 Print("Too Hot") Else Print("Perfect temp!") End
What if we need to check if the temperature is too hot or too cold? It is possible to have an if statement inside another if statement. This is okay when using large programming languages, like Python or C#. However, we recommend only using it in DUE Script when necessary.
t = 30 If t > 40 Print("Too Hot") Else If t < 10 Print("Too Cold") Else Print("Just Perfect") End End
Here is the code that is doing the same but without using any nested if statements. You will learn about && in other lessons.
t = 30 If t > 40 Print("Too Hot") End If t < 10 Print("Too Cold") End If (t >= 10) && (t <= 40) Print("Just Perfect") End
You are nearly done with the basics of the language, but we still need to learn about operators.
Is there any difference between how humans and computers when it comes to “if”? Computers are very “black and white” with no grey in between. If we program a robot car to cross the intersecting when the traffic light is green, the robot car will do just that without taking in any other variables. Would you cross if there is a person/car in front of you? To us, this is automatic as our brains make millions of decisions around the clock. Teaching a machine to mimic what we do and factor it all in requires very sophisticated software. This is called artificial intelligence. And even then, how do you teach a machine to have feelings?