We’ve seen in a previous article about Python’s If Statement how we write our If statement to change the flow of our program, only running some code based upon if certain conditions are met.
We’re going to continue that notion, but increase the complexity of our If Statement.
Multiple Statements
A common occurrence is we need to check not one, but two conditions. For example, in the United States, you need to register for Selective Service if you 18 or older and Male. Since there are two conditions, you could write two If Statements, one nested inside the other, but that gets complicated and messy with keeping track on indenting.
The And Operator
The easier way is to use the and operator. It says that two conditions must both be true. If so, then the If Statement is true, and the true block of code will run.
Consider the following block of code.
if age >= 18 and gender = "M" :
# true block of code
Python uses Short Circuit Logic. That means that if the first condition is false, it won’t bother to check to see if any of the other conditions – thus speeding up the application. In that manner, if you can, put the one most likely to be false first – that way if it fails, you don’t “waste” time checking other conditions.
You can have more than two conditions checked if you want. You just need to join each one with an additional and operator.
The Or Operator
Sometimes you need to check to see if one of two conditions is true. It doesn’t matter if only one is true, or both. In that case, you can use the or operator. If either one is true, the whole condition is considered true.
For example, you might put on a jacket if it is cold or if it rainy. Consider the following code.
if raining == true or cold == true :
print("Wear a jacket.")
No matter which one is true, or if they are both true, the true block will execute. The Or statement also uses Short Circuit Logic – thus once it finds any condition to be true, it stops checking and considers the whole thing to be true.
Boolean Variables
Now our conditions check for a true false value. However, there is a type of variable that can store a true/false value only. These are called a Boolean variable.
So we could store a condition inside that variable, or we could just store that value if we are using the variable as a flag. This means we can simplify our code even further. If we look at our previous example, we can rewrite it as:
if raining or cold :
print("Wear a jacket.")
If Statements – More Advanced Forms was originally found on Access 2 Learn