Python Conditional Statements

Discover how python conditional statements control the flow of programs using logical and comparison operators.

Python conditional statements allow you to execute different code blocks based on certain conditions. There are three main Python conditional statements: if, elif, and else. This article discusses how each of these statements works and shows some examples of them in use. Let's get started!

Python uses the logical and comparison operators to create Boolean values, which can then control the flow of your program. Get some of the most common operators below.

Operator Functionality.
== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
and Returns true is both statements are true
or Returns true if either statement is true

If statement

If statements are the most basic Python conditional statement. They allow you to execute a certain code block only if a certain condition passes. For example, let's say we have a list of numbers and want to print out all the even numbers in the list. We can use the if statement like so:

``````numbers = [0,  15, -20, 30, 45] # Define our list of numbers

for num in numbers:        # Iterate through each number in the list
if num % 2 == 0:        # If the number is evenly divisible by two...
print(num)         # ...print it out!```
``````

Returns

0

-20

30

In this example, we iterate through each number in our list. For each number, we check to see if it is evenly divisible by two using the modulo operator (%). If it is, we print it out. Otherwise, we do nothing.

Elif statement

Elif statements are Python conditional statements that come after an if statement. The elif keyword represents "else if". It allows you to chain multiple conditions together. Elif statements only execute if the condition in the if statement is not met. For example, let's say we have a numbers list and want to print out all the positive numbers in the list. We can do this with an elif statement like so:

``````numbers = [-15, -20, 0, 15, 30, -2, 4] # Define our list of numbers

positive = []
negative = []

for num in numbers:          # Iterate through each number in the list
if num > 0:              # If the number is greater than zero...
positive.append(num) # Add num to the end of positive list
elif num < 0:            # elif the number is less than zero...
negative.append(num) # Add num to the end of negative list

print("Postive numbers from the list", positive)
print("Negative numbers from the list", negative)
``````

Returns

Postive numbers from the list [15, 30, 4]

Negative numbers from the list [-15, -20, -2]

In this example, we iterate through each number in our list. For each number, we check to see if it is greater than zero. If it is, we add the number to the end of the positive list. Otherwise, for each number, we check to see if it is less than zero and add it to the negative list. Notice that we don't need an else statement here because the elif statement will catch all other cases.

Else statement

Else statements are Python conditional statements that come after an if or elif statement. They are only executed if the condition in the if or elif statement is not met. For example, let's say we have an age and want to check if the age is for a kid, teenager, or adult. We can do this with an else statement like so:

``````age = 12  # Define the number

if age < 13:                   # If the age is less than thirteen...
print("You are a kid")     # ...print
elif age > 12 and age < 18:    # elif the number is greater than twelve and less than 									eighteen)...
print("You are a teenager")# ...print!```
else:
print("You are an adult")  # else print!!
``````

In the example above, we check the age to see if it is less than 13 and print "You are a kid." Otherwise, If it is greater than 12 and less than 18, we print "You are a teenager." Otherwise, we print "You are an adult." This else statement will catch all other cases that the if, and elif statements don't.

`Note`

1. You can have more than one elif statement between the initial if and the else. However, once Python finds a condition that evaluates to true, it skips all the remaining conditions. In other words, only one code block will execute for an if-elif-else statement.

2. You cannot use else without an if. If you try to do so, you will get a syntax error. The same goes for elif; it must always come after an if (or another elif).

Returns SyntaxError: invalid syntax

Indentation

Python conditional statements are written using indentation. The Python interpreter uses the indentation to determine which code block belongs to which condition. For example, take a look at the following code:

``````age = 21
if age > 17:
print("You can vote")
``````

You'll first notice that the Python if statement is followed by a colon (:). This is how Python knows that everything indented after the if statement belongs to that condition. In this case, Python will execute the print statement only if the condition (age > 17) is true. Otherwise, it will skip over that code block.

`Note`

All code within a block must indent the same amount. The standard indentation is four spaces, although you can use tabs as long as they translate to four spaces.

That's all there is to Python conditional statements!

Conclusion

Python conditional statements are very powerful and can be used to do some cool things. For example, they allow you to execute different pieces of code based on whether a specific condition passes or not. In this article, we've only scratched the surface of what Python conditional statements can do. Check out the official Python documentation to learn more about Python conditional statements. Thanks for reading!

Until next time! :)

If you enjoy our content, please consider buying us a coffee to support our work: