5 if … else Conditional Execution
Python
We can test a logic statement like a > b
and do something different depending on whether it is true or false.
if a > b:
max = a
else:
max = b
print(max)
will set the value of max to the largest of the two values and print it. In words: If it is true that a
is greater than b
, then set max
to the same value as a
, otherwise (else
) set max
to the same value as b
. This Python code is easy to read because the indentation provides both a visual cue to a human reader and defines the scope of the two blocks of code for interpretation by the computer. We can stretch out the decision tree to more options like this:
if a > b:
max = a
elif b > c:
max = b otherMax = b
else:
max = c
print(max)
The blocks of code can contain multiple instructions, and could include more nested conditions inside the blocks. The format is different in different languages, but the idea is exactly the same.
C
The same task would look a little different in Arduino C, but mostly in the punctuation needed to mark off each block of code with curly braces and to end each statement with a semicolon. The logical statements being tested must also be included in parentheses. The indentation and line breaks make it easy for a human to see the structure, but the C language requires the explicit punctuation to inform the compiler.
if (a > b) {
max = a;
} else if (b > c) {
max = b; otherMax = b;
}
else {
max = c; }
Serial.print(max);
This line would be seen as the same thing by the compiler even though much harder for us to read:
if(a>b){
max=a;
}else if(b>c){
max=b;otherMax=b;
}else{
max=c;}
Serial.print(max);
I often find myself Googling things like “python if” or “matlab if” or “swift if” or “fortran if” or “pascal if” in order to remind myself about the syntax for a particular language. C is the only language I have used regularly enough throughout my career to usually remember the syntax of basic statements and that should be fine for you as well.
MATLAB
The idea remains exactly the same, but the MATLAB syntax is a little different again:
if a > b
max = a;
elseif b > c
max = b; otherMax = b;
else
max = c; end
The end marker and line breaks help the computer interpret the meaning.