When learning the basics of Python, all the code you write will be executed in sequence. Sequential execution means that all code is executed in the order that it is written. As a result, you can’t exclude certain parts of code. This is fine when learning the basics. However, because real world programs are often more complicated, there will be times when code only needs to be executed when certain conditions are met. To facilitate this, we need to use conditional logic.

The simplest form of conditional logic: the if statement

Let’s start with the if statement. The if statement is one of the most often used statements to control the flow of code execution. This is the syntax:

if <expression>:

There are two important things to note about this syntax. The first thing is the colon (:) after the expression. The colon indicates to Python that a statement is coming. Therefore, it’s required syntax!

The second thing to note is the indentation of the statement. Python code needs to be indented properly, because it tells Python how the statements are grouped. I recommend reading this part of the Python Documentation for more information.

Conditional Logic in Python and the Importance of Indentation

The expression will be evaluated as a Boolean, as I explained in my article about the usage of operators in Python. Say you want to code a program that compares two numbers and prints something based on the result of the comparison. It would look like this:

x = 3
y = 5

if x == y:
	print("x (3) does not equal y (5), so this WILL NOT print")

if x < y:
	print("x (3) is smaller than y (5), so this WILL print")

if x > y:
	print("This won't print either, of course!")

As seen in the example, the syntax is quite simple. However, it’s also quite limited in it’s functionality. Right now, we can conditionally execute a single statement or a code block containing several statements if our expression evaluates to True. But what if you want to execute another statement if it evaluates to False? That’s where the else and elif clauses come into play.

Logical Operators: AND, OR & NOT

Up until now, we’ve only seen one expression in the if statement. However, logical operators allow to evaluate whether two or more expressions are true or not true. For example, they can be used to determine if a number is larger than 10 and lower than 50. Or determine if a number is either higher than 200 or lower than 700.

Logical Operators

You can see the exact syntax in this example:

x = 25

if x < 30 and x > 5:
        # when using and, all the expressions must be True
    print("This will print, because X is both smaller than 30 and larger than 5.")
if x > 50 or x > 20:
    # when using or, only one of the expressions must True
    print("This will print, because while X is smaller than 50, it is higher than 20")

if not x > 50:
    # when using not, it will check if the opposite is True
    print("This will print, because x is NOT larger than 50, so the expression is True")

 # ------------------------------------------------------------------------------------------

if x < 30 and x > 25:
    # when using and, all the expressions must be True
    print("This won't print, because while x is smaller than 30, it's not larger than 25 (it's equal)")
if x > 50 or x > 30:
    # when using or, only one of the expressions must be True
    print("This will not print, because x isn't larger than either 50 or 30")

if not x > 20:
    # when using not, it will check if the opposite is True
    print("This will not print, because while x is larger than 20, by using NOT, we check for the opposite, so the expression is False")

The else and elif clauses

In Python (and most other programming languages), the else clause expands on the if statement to conditionally execute one or multiple statements. Any else statement will execute only if the first expression (the initial if statement) evaluated to False. If the initial statement evaluates to True, then the else statement is skipped.

x = 50

if x > 100:
	print("X is larger than 100!") # this won't run, because 50 is smaller than 100 (it's False)
	print("X is smaller than 100!") # instead, this will run!

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

x = 22

if x < 100:
	print("X is smaller than 100!") # this will run, because 22 is smaller than 100
	print("This won't run!") # this will be skipped, because the initial expression was True!

There is also syntax to create more alternatives for when the initial expression is False. This is called the elif clause, which is short for else if. You can have multiple elif clauses and each of them will be evaluated. If one of them is True, the remaining elif’s are skipped. If all of them evaluate to False and there is an else clause specified, then that is executed.

my_number = 50

if my_number > 90:
    # this won't run, because my_number (50) is smaller than 90
    print("My number is larger than 20!")
elif my_number == 50:
    # this will run, because my_number is equal to 50
    print("My number is smaller than 50")
elif my_number < 60:
    # this won't run, because even though my_number is smaller than to 60, the first
    # elif already validated to true. Anything after this won't be executed.
    print("My number is smaller than 50")
	# The else statement is the "final" statement. If none of the others would validate to True, this would be executed.
	print("This won't run!")

Finally, if there is no else specified and none of the other expressions are True, then nothing will run!

Wrapping up

Hopefully this article helped you understanding the basics of conditional logic in Python. As always, the best way to fully grasp all of this is by trying everything yourself. Feel free to take the examples I provided and modify them. If you want to combine this with user input to create a more complicated, be sure to read my article on user input as a refresher. That’s all for now!

Let me know if this was helpful or if you would like to see more of these types or articles in the future. As always, if you have questions or concerns, feel free to comment below. Lastly, make sure to share the article if you liked it!

There are currently no comments.

This site uses Akismet to reduce spam. Learn how your comment data is processed.