Mastering Comparison Operators and if
Statements in Python
Welcome back to my introduction to Python written course! The previous article explored functions and return values in detail, returning values, code style, and consistency.
In development, it is often necessary to compare values and execute different code blocks based on the results of those comparisons. This process is known as branching, an important concept in programming. There are several tools that Python provides for branching (Conditional Statement), including comparison operators, if
statements, else
statements, and elif
statements.
This article explores using these tools to create branching logic in Python. We will discuss how to compare values, how to use if
statements to execute code based on the results of those comparisons, and how to use else
and elif
statements to add additional branching logic. By the end of this article, you will have a good understanding of how to use branching to control the flow of your Python code.
Comparing values in Python
In Python, we can compare values using comparison operators. These include:
==
: equal to!=
: not equal to>
: greater than<
: less than>=
: greater than or equal to<=
: less than or equal to
These operators return a Boolean value of True
or False
. Here are some examples:
# Comparing integers
1 == 1 # True
1 != 2 # True
2 > 1 # True
2 < 3 # True
2 >= 2 # True
2 <= 3 # True
# Comparing strings
'hello' == 'hello' # True
'hello' != 'world' # True
'hello' > 'goodbye' # True
'hello' < 'world' # True
'hello' >= 'hello' # True
'hello' <= 'world' # True
We can also compare objects of different types, such as strings and integers:
# Comparing a string and an integer
'2' == 2 # False
'2' != 2 # True
'2' > 2 # False
'2' < 2 # False
'2' >= 2 # False
'2' <= 2 # False
It’s important to note that objects of different types are compared based on their types rather than their values. In the example above, the string '2'
is not equal to the integer 2
, because they are different types.
Branching with “if” Statements
In Python, we can use branching to execute different code blocks based on the comparison results. We do this using if
statements.
Here’s an example:
x = 28
if x > 0:
print('x is positive')
In this example, the code block indented under the if
statement will be executed if the comparison x > 0
is True
.
Careful with your indentation
In Python, indentation is used to define code blocks. When writing a if
statement, the code that should be executed if the comparison is True
should be indented under the if
statement. This indentation is essential because it tells Python which lines of code belong to the code block. If the indentation is not correct, Python will raise an error:
x = 28
if x > 0:
print('x is positive') # This line is not indented correctly
In this example, the first print
statement is not indented under the if
statement, so Python will consider it to be a separate statement and will raise an IndentationError
when it is executed.
Here is the error message that would be displayed when this code is run:
IndentationError: expected an indented block
The following example is indented correctly, the interpreter won’t raise an error, but you must ensure that it has the expected behavior:
x = 28
if x > 0:
print('x is positive')
print('This line is also part of the code block')
print('This line is not part of the code block')
In this code, the first two print
are indented under the if
statement, so they are part of the code block that will be executed if x > 0
. The third print
is not indented, so it is not part of the code block and will be executed regardless of the value of x
.
Maintaining consistent indentation throughout your code is essential, as it can significantly impact the behavior of your program. Always ensure that the indentation of your code blocks is correct, as it is a crucial part of the Python syntax.
Using “else” statement
We can also add an else
statement to execute a different code block when the comparison is False
:
x = 28
if x > 0:
print('x is positive')
else:
print('x is not positive')
Using “elif” statement
If we want to check multiple conditions, we can use elif
(short for "else if") statements:
x = 28
if x > 0:
print('x is positive')
elif x < 0:
print('x is negative')
else:
print('x is zero')
In this example, the first code block will be executed if x > 0
is True
, the second code block will be executed if x < 0
is True
, and the third code block will be executed if both comparisons are False
.
It’s important to note that only one code block will be executed in a if-elif-else
statement. Once a code block is executed, the rest of the statement is skipped.
Nested branching
We can also nest if
statements within other if
statements to create more complex branching logic:
x = 28
y = 14
if x > 0:
if y > 0:
print('x and y are both positive')
else:
print('x is positive, y is not')
Logical operators
In Python, we can use and
, or
, and not
operators to create complex branching logic that checks multiple conditions. These operators allow us to check if multiple conditions are True
or False
at the same time, and to negate a condition.
"and"
operator
The and
operator allows us to check if multiple conditions are True
at the same time. It returns True
if all conditions are True
, and False
if any of the conditions are False
.
Here’s an example:
x = 28
y = 14
if x > 0 and y > 0:
print('x and y are both positive')
In this example, the code block will be executed if both x > 0
and y > 0
are True
. If either comparison is False
, the code block will not be executed.
"or"
operator
The or
operator allows us to check if at least one of multiple conditions is True
. It returns True
if any of the conditions are True
, and False
if all of the conditions are False
.
Here’s an example:
x = 28
y = -10
if x > 0 or y > 0:
print('x or y is positive')
In this example, the code block will be executed if either x > 0
or y > 0
is True
. If both comparisons are False
, the code block will not be executed.
"not”
operator
The not
operator allows us to negate a condition. It returns the opposite Boolean value of the condition it is applied to.
Here’s an example:
x = 28
if not x > 0:
print('x is not positive')
In this example, the code block will be executed if x > 0
is False
. If x > 0
is True
, the code block will not be executed.
Add parenthesis to create more complex conditions
We can use these operators along with parenthesis to create complex branching logic. For example:
x = 28
y = -10
if (x > 0 and y > 0) or (x < 0 and y < 0):
print('x and y have the same sign')
else:
print('x and y have different signs')
In this example, the code block will be executed if either (x > 0 and y > 0)
or (x < 0 and y < 0)
is True
. If neither of these conditions is True
, the code block in the else
statement will be executed.
Using a truth table can be helpful
A truth table is a table that shows the possible inputs and outputs for a logical expression. It is a helpful tool for understanding how logical expressions work and testing your code's behavior.
Here is an example of how to construct a truth table for the and
or
and not
operator:
In this article, we have discussed the tools that Python provides for comparing values and branching based on the results of those comparisons. We have covered comparison operators, if
statements, else
statements, and elif
statements, and we explored how to use these tools to create branching logic in Python. We have also discussed how to use and
, or
, and not
operators to create multiple conditions.
Whether you are a beginner learning Python for the first time or an experienced developer looking to brush up on your skills, knowing how to use these tools effectively is essential to becoming a proficient Python programmer.
I hope this article has been helpful in your journey to learn Python. In the following article, we’ll talk about loops, compound assignment operators, and recursion and explore their differences.
Stay tuned, and let’s code!
If you’re interested in reading other articles written by me. Check out my repo with all articles I’ve written so far, separated by categories.
Thanks for reading