In this tutorial, you’ll learn about if-statements, using which you can do certain things only if certain conditions are met. In plain English, if-statements correspond to “Do this; then do that.” or “If this condition is true, perform this action; otherwise, do that action.”
A good way to visualize if-statements is flow charts. If-statements represent the yes / no questions in the flowchart below.
Before getting into if-statements, you’ll first learn how to compare things in Python as well as the Boolean data type (values
A big part of programming involves comparing things. What’s the easiest thing to compare? Numbers, of course. Let’s see how that works:
print(5 > 2) # Output: True print(3 < 1) # Output: False print(5 > 2 * 2) # Output: True print(1 == 1) # Output: True print(5 != 2) # Output: True
You may be wondering why we put two equal signs
== next to each other to compare if numbers are equal?
Since we use a single
= for assigning values to variables, Python syntax requires from us that we always put two of them, so
== , if we want to check if things are equal to each other.
We can also check if two things are unequal to each other. For that, we use the symbol
!=, as we saw in the example above.
In fact, each side of a comparison can be a longer expression as well. Let’s see it in action:
print(len("Commonlounge") > 10) # Output: True print(len("David") > 10) # Output: False
Give Python two more tasks:
print(6 >= 12 / 2) # Output: True print(3 <= 2) # Output: False
<, but what do
<= mean? Read them like this:
>y means: x is greater than y
<y means: x is less than y
<=y means: x is less than or equal to y
>=y means: x is greater than or equal to y
We’ve summarized the list of comparison operators in Python in a table at the end of the article.
We can also do multiple comparisons in one expression. We can use
not operators to combine multiple boolean values. Here’s an example:
print(6 > 2 and 2 < 3) # Output: True print(3 > 2 and 2 < 1) # Output: False print(3 > 2 or 2 < 1) # Output: True
You can give Python as many numbers to compare as you want, and it will give you an answer! Pretty smart, right? Here are the three boolean operators in detail:
- and – if you use the
andoperator, both comparisons have to be
Truein order for the whole command to be
- or – if you use the
oroperator, only one of the comparisons has to be
Truein order for the whole command to be
- not — not operates on just one Boolean value, and as you’d expect, flips it. So,
As we’ve done with examples before, let’s see the step-by-step evaluation of one of the above expressions to make sure everything is crystal clear.
3 > 2 and 2 < 1 => True and 2 < 1 => True and False => False
Have you heard of the expression “comparing apples to oranges”? Let’s try the Python equivalent:
print(1 > 'python')
Traceback (most recent call last): File "", line 1, in TypeError: unorderable types: int() > str()
Here you see that just like in the expression, Python is not able to compare a number (
int) and a string (
str). Instead, it shows a TypeError and tells us the two types can’t be compared together.
Incidentally, you just learned about a new type of object in Python. It’s called Boolean.
There are only two Boolean objects:
But for Python to understand this, you need to always write it as
True (first letter uppercase, with the rest of the letters lowercased). true, TRUE, and tRUE won’t work – only True is correct. (The same applies to
False as well, of course.)
Booleans can be variables, too! See here:
a = True print(a) # Output: True
You can also directly assign the value of a comparison:
a = 2 > 5 print(a) # Output: False
Practice and have fun with Booleans by trying to run the following commands:
True and True
False and True
True or 1 == 1
1 != 2
Congrats! Booleans are one of the coolest features in programming, and you just learned how to use them!
You can now move on to an essential tool in programming.
Lots of things in code should be executed only when given conditions are met. That’s why Python has something called if statements.
Take a look at the following code.
if 3 > 2: print('It works!')
In the first line, we have the if statement. Take a moment to notice the
: at the end of the line. This is an important part of the if syntax.
In the next line, we give further instructions to Python which are executed if the condition
3 > 2 turns out to be true (or
True for that matter).
Notice how we’ve indented the next line of code by 4 spaces? We need to do this so Python knows what code to run if the result is true. You can do one space, but nearly all Python programmers do 4 to make things look neat. A single
tab will also count as 4 spaces. In fact, all the lines following the if statement that are indented by the same number of space are considered part of the
if body, i.e., all of them will be executed if the
if statement evaluates to
True. For example:
if 3 > 2: print('It works!') print('This line also gets printed')
It works! This line also gets printed
Exercise: Write an if statement to check if the number entered by someone is greater than 100. You can write the code below by replacing the
a = input() int_a = int(a) if ... print('The number is greater than 100')
What if a condition isn’t True?
In the previous example, code was executed only when the condition was True. But Python also has
else statements for cases if your original if statement wasn’t
if 5 < 2: print('5 is less than 2') else: print('5 is indeed greater than 2')
When this is run it will print out:
5 is indeed greater than 2
If 2 were a greater number than 5, then the second command would be executed. Let’s see how
name = 'Dave' if name == 'Commonlounge': print('Hey Commonlounge!') elif name == 'Dave': print('Hey Dave!') else: print('Hey anonymous!')
Here’s the output:
See what happened there?
elif lets you add extra conditions that run if the previous conditions fail.
You can add as many
elif statements as you like after your initial
if statement. For example:
volume = 57 if volume < 20: print("It's kinda quiet.") elif 20 <= volume < 40: print("It's nice for background music") elif 40 <= volume < 60: print("Perfect, I can hear all the details") elif 60 <= volume < 80: print("Nice for parties") elif 80 <= volume < 100: print("A bit loud!") else: print("My ears are hurting! :(")
Python runs through each test in sequence and prints:
Perfect, I can hear all the details
Let’s dive deeper and see what’s happening in this code.
- On line 2, we check if the
volumeis less than 20. It isn’t, so we skip to line 4.
- On line 4, we check if the
volumeis greater than or equal to 20 or less than 40. It isn’t, so we skip to line 6.
- On line 6, we check if the
volumeis greater than or equal to 40 or less than 60. Since that’s the case (
volumeis 57), we print out
Perfect, I can hear all the detailson line 7.
- Once we’re done with line 7, we do not visit any of the subsequent elif or else blocks, and we just reach the end of the if…elif…else block, and there’s nothing left to do.
Note that in chained if … else if … else statements, only the first condition that is met gets executed. As soon as the first condition is met, none of future
elif) conditions will be considered. Hence, the earlier code could be written more concisely as:
volume = 57 if volume < 20: print("It's kinda quiet.") elif volume < 40: print("It's nice for background music") elif volume < 60: print("Perfect, I can hear all the details") elif volume < 80: print("Nice for parties") elif volume < 100: print("A bit loud!") else: print("My ears are hurting! :(")
We’re making use of the fact that, when we compare
volume < 60 (for example), all the previous conditions must have been
False. This automatically implies that
volume >= 40 (since the first two conditions were
False). The code might be slightly harder to read, but it is equivalent to the previous one.
When we looked at errors earlier, you may recall that we showed you a simple
print(5 / 0)
Gives the output:
ZeroDivisionError: integer division or modulo by zero
Let’s see what happens if we make an error in an if statement that isn’t run:
if(1 > 2): print(5 / 0) else: print("All is good!")
If we run this, we get the output:
All is good!
Wow! You may not have expected that. This is a really important concept that you’re learning for the first time — it’s called dynamic or lazy evaluation. Python is very lazy. It saves time by skipping over blocks of code that it doesn’t need to execute. In the above statement, since the if statement condition is
False, the code inside the if block isn’t run. Note that the Python interpreter will still flag the syntactical errors like the ones below:
if(1 > 2): print(5 / 0 else: print("All is good!")
SyntaxError: invalid syntax
Similarly, be careful of declaring any new variables inside the if statements. For example:
a = int(input()) b = 0 if(a > 0): b = a else: c = 0 print(b, c)
Here, for values of input a greater than 0, our code will throw the following error as expected:
NameError: name 'c' is not defined
Since a is greater than 0, the if statement is True and the code completely skips over the else block. Thus the variable c never gets defined, and line 8 throws the error.
In the last few exercises you learned about:
- comparing things – in Python you can compare things by using
- Boolean – a type of object that can only have one of two values:
- if … elif … else – statements that allow you to execute code only when certain conditions are met.
- Dynamic evaluation — Python is lazy and skips evaluation of statements it doesn’t need to execute.
The following is a list of all comparison operations supported by Python.
Operator | Example | Result | Description ---------|---------|--------|-------------------------------- == | 4 == 5 | False | is equal to != | 4 != 5 | True | is not equal to > | 4 > 5 | False | is greater than < | 4 < 5 | True | is less than >= | 4 >= 5 | False | is greater than or equal to <= | 4 <= 5 | True | is less than or equal to
Based on content from https://tutorial.djangogirls.org/en/python_introduction/