IF, ELSE and ELIF statements (conditional statements) allow us to build algorithms to create different outputs depending on whether a logical statement, such as whether a variable is equal to a certain value, is true or false. The statements can be based on the values stored in a variable or multiple variables and we can stack these statements to create complex decision logic within our code.
In real life we might decide to wear a coat when we leave home if the temperature is forecast to be below 10 degrees and not wear a coat if the temperature is 10 degrees or above. Here we evaluate the statement that the temperature is below 10 degrees and determine if it is true or false. If it’s true then the outcome is that we will leave home with a coat on. The process works the same when we program with IF, ELSE & ELIF statements. Let’s look at how to implement these statements in Python.
In the above scenario, if the logical statement that temp < 10 is true then we get an output that tells us to wear a coat. If the statement is false however then nothing happens but we might want a different output in this case. We can do this using an ELSE statement.
Now suppose the temperature is forecast to be above 10 degrees, making the statement evaluate to false. However, instead of just leaving our coat at home we want to also check if there is rain forecast. If this is true then we’ll want to take a waterproof. We can implement this using an ELIF statement.
The ELIF statement allows us to stack multiple conditional statements to handle potentially complex decisions in our code.
In our examples above, we only considered one variable in our statements but we can use as many as required to define the condition we are trying to evaluate. How these evaluate will depend on which of the operators (OR, AND, NOT) we use and in what combination.