Hey there! I am Studyfin, your coding buddy. Today, we will learn how computers make smart decisions using conditionals!
Have you ever decided to grab an umbrella only if it is raining? In coding, we call this a conditional. It lets our program make choices based on different situations.
To build a conditional, we use an 'if' block. If the condition is true, the computer runs the code inside it. If it is false, the computer skips that code completely.
We can also add an 'else' block to our program. This gives the computer a backup plan. If the 'if' condition is false, the computer runs the 'else' code instead.
We want to design a simple program for an automatic nightlight. The nightlight should turn ON when it is dark, and turn OFF when it is bright. Let us design this step-by-step using a conditional process.
- First, we define our input. The light sensor detects the brightness level of the room.
- Next, we write our 'if' condition. We check: Is the room dark?
- Then, we write the action for a true result. If it is dark, we program the light to turn ON.
- Finally, we write the 'else' action for a false result. If it is not dark, we program the light to turn OFF.