Lesson Contents
Until now, all code that I showed you was executed sequentially. Each and every line was executed, nothing was skipped. Sometimes, we only want to run our code when it matches specific criteria. We use the if, elif, else statements to make decisions.
In these examples, I use comparison and logical operators to compare values.
If
Take a look at the code below:
We have a variable named “ios_version” with integer 15. In our if statement, we check if variable “ios_version” equals 15. If so, we print a message. Our code ends with a general print message.
If we don’t have a match, it won’t print the first message. Let’s change our “ios_version” variable:
Our code doesn’t print the first message because it doesn’t match the if statement.
Shorthand If
When your if statement consists of a single line, you can also use the shorthand notation. Here is an example:
This saves some space and could make your code easier to read.
Nested If
We can also use nested if statements. This can be useful if you want to check multiple conditions. Consider the code below:
We see both print messages. The first if statement matches, which is why it prints the first message and runs the second if statement. The second if statement also matches, which is why it prints the second message.
Else
When you don’t have a match with the if statement, everything else matches the else statement. Here is a quick example:
We don’t have a match with the if statement, so it matches our else statement and presents us the “CPU load is OK!” message.