![]() | If |
A program lets a computer follow instructions, but so far the computer doesn't know how to make decisions.
With the "if" instruction, a computer can compare two things and make a decision. One way it can compare things is to check if two things are the same.
You do this by typing "if" with an opening bracket after it. Then you write the first thing you want the computer to look at. Then you type two equals signs and then the second thing you want the computer to look at. After that, you type a closing bracket, and then an opening "curly brace". You then give the computer some instructions that the computer should follow if the two things ARE the same. Then you type closing curly brace.
In this little program, if you answer yes, the computer will tell you to bring an umbrella. If you type something that isn't exactly the same as "yes" then the computer won't do anything. You can type "no" or "nope" and the computer won't do anything. If you use different letters like "yEs", it's not exactly the same as "yes" and the computer will also not do anything.
An exclamation mark followed by an equals sign means "not equal." In the program above, it first checks to see if you typed "yes." If so, it tells you to bring an umbrella. Then it checks to see if you typed something other than "yes." If so, it will tell you to wear sunscreen instead.
Instead of having two different if instructions, you can use the else instruction. In the above program, if a is "yes," then it does one thing. If a isn't "yes" then it does the instructions that come after the else. Also notice that you can have more than one instruction inside of the curly braces. And you can put things on different lines to make things easier to read.
This is useful because you can have lots of if instructions all put together. Here, if you type in "sunny," "rainy," or "snowy" the computer will tell you what to wear. If you type something else, the computer will go right to the end and tell you that it does not understand what you typed.
On the left, you need to write the program for a paint-mixing machine. It uses red, blue, and yellow paint to make other types of paint.
The command machine.order() asks what type of paint to make. It then gives you a string with the name of the paint. You then have to get the machine to make that type of paint. First, you must use machine.conveyor(), to move the paint bucket under the sprays on the conveyor belt. red.spray(), blue.spray(), and yellow.spray() will shoot paint into the bucket to make the right type of paint. Then machine.conveyor() again will move the paint away, and then the paint will be checked to see if it's correct. Can you write a program that can make all the different types of paint?