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.
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.
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.
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.
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.
It’s also possible to use the shorthand notation for else statements. This could be useful if you only have a single action under your statements.
This is a nice one-liner that makes our code a bit shorter.
It’s possible to add multiple if statement by using the elif statement. Take a look at this code:
We don’t have a match with the first if statement, but it does match our elif statement. This is why our code shows us the second message. You can have multiple elif statements if you want.