If Else Statements
Up to this point, you have not learned how to make certain statements run only if some condition is True
or False
.
What if you want to run code only if a certain condition is True
?
This is where if-else statements come in.
Let's look at a real life example:
If it's raining outside, then I'll bring my umbrella.
Otherwise, I won't bring my umbrella.
Here's what this logic would look like in Python.
if raining == True:
bring_umbrella = True
else:
bring_umbrella = False
Note the indentation of the code! Python is sensitive to the spacing, or whitespace within your code.
You can have as much indented, or nested code under each condition, and Python will run them from top to bottom, like it was written by itself.
A condition is anything that can be evaluated to either True or False. This includes variables, numbers, strings, and even functions.
Here are some examples:
- Is it raining? (
raining == True
) - Is it sunny? (
raining != True
) # != means "not equal to" - Is x greater than y? (
x > y
) - Is string
"Hello"
equal to string"Hello"
? ("Hello" == "Hello"
)
Advanced
What if we don't use an equality check to check if a condition is true? That is, we don't use any of these operators (==
, !=
, <
, >
, <=
, >=
).
We can just put the condition into the if-else statement like this:
if is_raining:
bring_umbrella = True
else:
bring_umbrella = False
Python will use the Truth Value of the condition to determine if it should run the code or not.
All objects in Python have a Truth Value. When used in if-else statements, the object will be tested for its truth value to determine if the nested operation should be tested.
- For integers, all non-zero values are considered True.
- For strings, all non-empty strings are considered True.
You can combine everything we learned to include if statements inside of other if statements, or combine multiple conditions with logical operators.
# The two following code blocks are equivalent
# Method 1 - Nesting
if is_raining:
if have_umbrella != True:
bring_umbrella = True
else:
bring_umbrella = False
# Method 2 - Combining
if is_raining and not have_umbrella:
bring_umbrella = True
else:
bring_umbrella = False