Initiation au code – Les conditions
TO BE OR NOT TO BE? IF NOT THEN WHAT?
Life is full of conditions: if you complete your homework, your mum will let me play, if you don’t, she will scold you; if you go to Domino’s on Wednesday you’ll get 50% off on the price, but if you go on any other day, you won’t get any discount, etc.
In the real world, you luckily have your brain to check what the condition is, whether it is met or not and respond accordingly. But a computer isn’t that lucky, unfortunately (or fortunately?). Even though it can perform every task at lightning fast speed, you still need to give instructions to performs those tasks; even checking the conditions. This is where the conditional statements come in handy. These statements give the program the ability to check the conditions by testing a variable against a value and act accordingly. A program that has conditional statements is called a Conditional Program, and the process is known as Conditional Programming.
The most common conditional statement is the if-else statement. This is how it works:
If (condition is evaluated to be TRUE)
Do only those things which are to be done if the condition evaluated to be True
Else
Do those things which are to be done if the condition is evaluated to be False
The flowchart above checks the following condition: Is today a Wednesday?
If yes, then you get a discount of 50% on the pizza, and you can enjoy a pizza. If not, then there is no discount. So, you cannot buy a pizza (This flowchart is perhaps made by a college student who lives in a hostel.).
Conditional Statements in Scratch
Scratch also has a simple if-else statement. This statement will check the following condition: if it evaluates to be true, then the program will take actions that are to be taken (these are actions are defined while writing the program) and then move onto the next step; if it does not evaluate to be true, then the program will not take any action and directly move to the next step.