If statements
What is a conditional?
A conditional is an expression that evaluates to either True
or False
. For example:
print(5 == 5) # True
The double equal sign is used to compare two things, and the result of the comparison will be either True
or False
. In this case, because both things are equal, the result is True
.
Here's some other comparisons:
!=
, not equal—the opposite of==
.>
and<
.>=
and<=
.
And here's examples of what they result in:
print(5 != 5) # False, because they are the same
print(6 == 5) # False, because they are different
print(6 > 5) # True
print(6 < 5) # False
print(5 > 5) # False, 5 is not greater than 5
print(5 >= 5) # True, 5 is greater than or equal to 5
What is an if statement?
Sometimes we want our programs to do different things depending on what the user does.
For example, if the user clicks a button we may want to do one thing—and if they click someplace else we could do something entirely different.
Handling different user inputs is essential so we can make programs that are dynamic and respond to what the user does.
An if statement is a way of handling that. In an if statement we start off by evaluating a conditional.
If the conditional evaluates to True
, we execute the body of the if statement. Like so:
learning_programming = True
if learning_programming:
print("You're awesome!")
The if statement is comprised of four parts:
- The
if
keyword, first of all. - The conditional, which must evaluate to
True
for the body to run (in the example above, the conditional islearning_programming
, which has the valueTrue
). - A colon (
:
) - In the next line and indented, the body of the if statement.
Indentation means adding some spaces in front of the line. Usually in Python when we want to indent the body of an if statement, we use 4 spaces.
Python needs indentation in order to work. It is not optional.
So in the example above, the body of the if statement, what we want to execute if the if statement conditional evaluates to True, has 4 spaces in front of it.
After the if statement we can add some unindented code (without the 4 spaces in front) and that code will run regardless of whether the if statement conditional evaluates to True
or False
, such as this:
if True:
print("We're in the if statement!")
print("Now we're not.")
Another example
age = 100
if age >= 100:
print("You can learn programming at any age!")
In this example we use a conditional which is calculated from a comparison—age >= 100
is True
, so the if statement will run.
What is its purpose?
Naturally if the values are hardcoded, such as in the example above, if statements are not needed. Instead of writing this:
age = 100
if age >= 100:
print("You can learn programming at any age!")
You could just write this:
print("You can learn programming at any age!")
However, they become much more useful when we're dealing with user input. Indeed we could do this:
age = int(input("Enter your age: "))
if age >= 100:
print("You can learn programming at any age!")
Now our program is dynamic, because depending on what the user enters we will print out something, or nothing. Only if they enter a number equal to or greater than 100, we will print something out.
Try it out in the editor below!
What is a compound if statement?
If we wanted to print something out even when the user enters less then 100, we could do that like this:
age = int(input("Enter your age: "))
if age >= 100:
print("You can learn programming at any age!")
if age < 100:
print("You're doing great!")
However, it's suboptimal. Imagine the user types in 100.
It's suboptimal because Python will check the first if statement—age >= 100
. It evaluates to True
so Python would run the print statement.
Then Python would check the second if statement. It evaluates to False
so Python does not run the print statement for the second if statement.
However, because we ran the first if statement we actually do not need to even check the second if statement. After all, if the first one evaluates to True
the second one cannot evaluate to True
(it's impossible for age
to both be greater than or equal to 100, and also less than 100).
Compound if statements allow us to chain these together so Python knows that as soon as one evaluates to True
, the rest can be ignored. We write them like so:
age = int(input("Enter your age: "))
if age >= 100:
print("You can learn programming at any age!")
elif age < 100:
print("You're doing great!")
And the great thing about this is that you can keep chaining them, as many as you want:
age = int(input("Enter your age: "))
if age >= 100:
print("You can learn programming at any age!")
elif age < 10:
print("Starting young!")
elif age < 100:
print("You're doing great!")
Notice that for that last example, we added elif age < 10
before elif age < 100
.
That's because if we do this:
age = int(input("Enter your age: "))
if age >= 100:
print("You can learn programming at any age!")
elif age < 100:
print("You're doing great!")
elif age < 10:
print("Starting young!")
The third if statement will never run. Here's why:
- Imagine the user enters
8
. - The first if statement checks whether
8 >= 100
—which isFalse
. - We go to the second if statement. It checks whether
8 < 100
—which is True.- We run the body of this if statement
- Because the three if statements are linked, we skip the last one.
We would print You're doing great!
instead of Starting young!
.
However if we reverse the two last ones, we would get what we want. Try it out!
The else
keyword
If you have a chained if statement that checks all possibilities, instead of defining all possibilities you can use the else
keyword.
Here's what I mean.
age = int(input("Enter your age: "))
if age >= 100:
print("You can learn programming at any age!")
elif age < 10:
print("Starting young!")
elif age < 100:
print("You're doing great!")
There are really three different classes of input:
- Numbers which are 100 or greater;
- Numbers which are less than 10;
- Every other number (between 10 and 99).
That last bullet point is key: every other number.
Basically what that means is:
- If the first if statement doesn't evaluate to
True
, we must have a number less than 100. - If the second if statement doesn't evaluate to
True
, we must have a number between 10 and 99. - The last if statement encompasses all remaining numbers that haven't already checked.
For this type of conditional, we don't have to say age < 100
. We can just tell Python to check "all remaining options".
We do that like so:
age = int(input("Enter your age: "))
if age >= 100:
print("You can learn programming at any age!")
elif age < 10:
print("Starting young!")
else:
print("You're doing great!")
What that means in English is:
- Check whether age is greater than or equal to 100;
- Check whether age is less than 10;
- Otherwise, print
"You're doing great!"
.
To recap, when you have a set of linked if statements that end with an else
, the else
part will always run if none of the other options run. That may be what you want in some cases, but not in others!
If you want more control over what runs and what doesn't, you can avoid using else
and instead just use elif
.
Truthyness and Falsyness in Python
In Python we can convert any value to a True
/False
value using the bool()
function.
The function is called bool()
because True
/False
values are called booleans.
The name comes from the mathematician that came up with the type of value, George Boole.
Wait... can you convert any value to a boolean?
Yep, any value can be converted to a boolean. That includes strings, numbers, lists, dictionaries, and everything else.
Here's what happens when you convert those to a boolean:
print(bool(5)) # True
print(bool("Rolf")) # True
print(bool(["Rolf", "Adam"])) # True
print(bool({"Rolf": 24, "Adam": 30})) # True
So, everything becomes True
?
Not exactly. Most things evaluate to True
. Here's what evaluates to False
:
- The first obvious one,
bool(False)
isFalse
. bool(None)
is alsoFalse
.None
in Python means "nothing" and it is a keyword. We'll learn more about it later on.bool(0)
,bool(0.0)
, and usually other zeros evaluate toFalse
.- Empty sequences like
bool("")
,bool([])
, andbool({})
evaluate toFalse
.
For more information on truth value testing in Python, check out the official documentation.
What does that mean for you?
Well, it means that you can craft if statements a bit more smartly with that knowldege.
If statements always use bool()
behind the scenes in the conditional. For example:
friends = ["Rolf", "Adam", "Anne"]
if friends:
print("You have friends!")
In the example above, the if statement is actually doing bool(friends)
, which evaluates to True
because it is a non-empty list. The print statement would execute.
Without the knowledge of truth value testing, you would have to do this:
friends = ["Rolf", "Adam", "Anne"]
if len(friends) > 0:
print("You have friends!")
If you do something like the above, it shows there is a small gap in your Python knowledge—because it's more verbose and complicated than the original solution for no real benefit.
Another option is when asking for user input, you can use your new knowledge to tell the user to make sure to enter some input:
user_input = input("Enter your age: ")
if not user_input:
print("Make sure to enter something!")
If you place not
in front of a value, it evaluates it as normal using bool()
, and then gives you the opposite boolean.
So not True
gives you False
, and not False
gives you True
.
Imagine user_input
is an empty string because the user did not enter anything (i.e. they pressed Enter without typing anything else).
Then not user_input
is the same as not bool("")
, which is equivalent to not False
. The result is True
.