The if else statement is a fundamental part of programming in any language, and Python is no exception. Thus, this structure allows you to execute different lines of code based on a condition , making your programs more flexible and efficient.
In this article, we will take a closer look at the if else statement in Python, including its syntax, usage, and some tips and tricks for using it effectively. So, we’ll also cover some common pitfalls to avoid when using if else statements, to help you write cleaner, more efficient code.
Table of Contents
Syntax
The if else syntax in Python is a control flow structure that allows you to execute different lines of code based on a condition. Thus, the basic structure of the if else syntax in Python is as follows:
if condition:
# code to be executed if condition is true
else:
# code to be executed if condition is false
A condition is an expression that evaluates to true or false. This way, if the condition is true, the code inside the block if
will be executed. Otherwise, the internal code else
will be executed.
Block if
and block else
are indirect, meaning we can omit one of them if we wish. For example, we will execute the code within the block if
if the condition is true, and there will be no code executed if the condition is false. Look:
if condition:
# code to be executed if condition is true
It is also possible to use several conditions within if
, separated by elif
(short for “if else “). For example:
if condition1:
# code to be executed if condition1 is true
elif condition2:
# code to be executed if condition2 is true
else:
# code to be executed if both conditions are false
In this example, condition1 is evaluated first. If true, the internal code if
will be executed. This way, if it is false, condition2 is evaluated. If true, the internal code elif
will be executed. Otherwise, the internal code else
will be executed.
It’s important to note that the conditions in if
and elif
are evaluated in sequential order, meaning that the second condition will not be evaluated if the first condition is true. Thus, we can use it to avoid evaluating unnecessary conditions.
In short, the if else syntax in Python is a control flow structure that allows you to execute different bits of code based on a condition. It can be used with one or more conditions, and the if
and blocks else
are specific.
Common Uses of the if else Structure in Python
The if else structure in Python is one of the most used in programming, and has several applications in different contexts. Here are some of the common uses of the if else structure in Python:
Simple condition check:
An if else structure can be used to check whether a condition is true or false. For example:
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
Thus, this example checks whether the variable x is greater than 5, and if so, it prints the message “x is greater than 5”, otherwise it prints the message “x is less than or equal to 5”.
Executing different codes conditionally:
An if else structure can be used to execute different code based on a condition. For example:
if condition:
# code to be executed if condition is true
else:
# code to be executed if condition is false
Thus, this example executes the code inside the block if the condition is true, otherwise it executes the code inside the else.
Use of elif to include several conditions:
An elif structure (short for “if else”) allows you to include multiple conditions in the same if else structure. For example:
if condition1:
# code to be executed if condition1 is true
elif condition2:
# code to be executed if condition2 is true
else:
# code to be executed if both conditions are false
This example checks if condition1 is true, and if so, executes the code inside if. So, if condition1 is false, check if condition2 is true, and if so, execute the code inside elif. If both conditions are false, run the inside else code.
How to use the if else structure in conjunction with other structures and functions in Python
Structure if-else
is important in Python because it allows you to control the flow of code, making writing programs easier and more efficient. This way, it allows checking conditions and executing different codes based on the results of this checking, making the code more flexible and adaptable to different situations. Thus, we can use it in conjunction with other structures and functions.
Using if else in conjunction with loops
Example 1: Using if else
inside a for
loop
In the example below we have the code defining a list of fruits and uses a “for” loop to iterate over the fruits in the list. If the current fruit is “apple”, it prints “I love apples!”. Otherwise, print “I don’t love” + fruit. Look:
fruits = ['apple', 'banana', 'blueberry']
for fruit in fruits:
if fruit == 'apple':
print('I love apples!')
else:
print('I don't love ' + fruit)
Output:
I love apples!
I don't love bananas
I don't love blueberries
Example 2: Using if else
inside a while
loop
In the example below we have the code that iterates over the list of fruits and checks if the current fruit is “apple”. If so, print “I love apples!” This way, otherwise it prints “I don’t love” + the current fruit. Look:
fruits = ['apple', 'banana', 'blueberry']
i = 0
while i < len(fruits):
if fruits[i] == 'apple':
print('I love apples!')
else:
print('I don't love ' + fruits[i])
i += 1
Output:
I love apples!
I don't love bananas
I don't love blueberries
Using if else in conjunction with functions
Example 1 : Using if else
with len
In the example below we have code that defines a list of fruits and checks if the list is empty. So, if it is not empty, it prints the list of fruits, one per line. Otherwise, it prints the message “No fruits.”. Look:
fruits = ['apple', 'banana', 'blueberry']
if len(fruits) > 0:
print('The fruits are:')
for fruit in fruits:
print(fruit)
else:
print('There are no fruits.')
Output:
The fruits are:
litter
banana
blueberry
Example 2 : Using if else
with range
In the example below we have the code that iterates from 1 to 5 and checks whether the number is even or odd, prints a message, See:
for i in range(1, 6):
if i % 2 == 0:
print(f'The number {i} is even.')
else:
print(f'The number {i} is odd.')
Output:
Number 1 is odd.
Number 2 is even.
Number 3 is odd.
Number 4 is even.
Number 5 is odd.
Example 3 : Using if else
with set
In the example below, the code checks whether the fruit “apple” is present in the “fruits” list. If so, print “The apple fruit is present in the list.”. Otherwise, it prints “The apple fruit is not present in the list.”. Look:
fruits = {'apple', 'banana', 'blueberry'}
if 'maçã' in fruits:
print('The apple fruit is present in the list.')
else:
print('The apple fruit is not present in the list.')
Output:
The apple fruit is present in the list.
Example 4 : Using if else
with null
In the example below we have the code checking the variable “name” is being defined. If so, print the value of the variable. Otherwise, it prints a message indicating that no name was provided. Look:
name = None
if name is not None:
print(f'The name is {name}.')
else:
print('No name was provided.')
Output:
No names were provided.
Example 5 : Using if else
with append
In the example below we have the code checking whether the “fruits” list has any elements. This way, if yes, it adds “blueberry” to the list and prints the list. Otherwise, it prints a message indicating that there are no fruits. Look:
fruits = ['apple', 'banana']
if len(fruits) > 0:
fruits.append('blueberry')
print(fruits)
else:
print('There are no fruits.')
Output:
['apple', 'banana', 'blueberry']
Using if else in conjunction with flow control structure
Example 1 : Using if else
with switch case
In the example below, the code checks the value of the “fruit” variable and prints a message. If the value is “apple”, “banana”, “blueberry” or “grape”, it prints a message saying that it is a common or less common fruit. Otherwise, it prints a message saying that it is not a fruit. Look:
fruit = 'apple'
if fruit == 'apple':
print('This is a common fruit.')
elif fruit == 'banana':
print('This is a common fruit.')
elif fruit == 'blueberry':
print('This is a less common fruit.')
elif fruit == 'grape':
print('This is a less common fruit.')
else:
print('This is not a fruit.')
Output:
This is a common fruit.
However, note that the use of switch case
in Python is uncommon, as the language has a more flexible and expressive flow control structure, called “ratio stanza” or “if-elif-else”. Instead of using switch case
, it is more common to use a series of if-elif
to check different conditions and run different code, as shown in the previous example.
Example 2 : Using if else
with if-elif-else
In the example below, we have the code checking the value of the “fruit” variable and printing a message. So, if the value is “apple” or “banana”, it prints “This is a common fruit”. This way, if the value is “blueberry” or “grape”, it prints “This is a less common fruit”. This way, otherwise it returns the string “This is not a fruit”.
fruit = 'apple'
if fruit == 'apple' or fruit == 'banana':
print('This is a common fruit.')
elif fruit == 'blueberry' or fruit == 'grape':
print('This is a less common fruit.')
else:
print('This is not a fruit.')
Output:
This is a common fruit.
Creating nested conditions using the if else structure
Nested conditions are a way to use the if else structure to check multiple conditions in a mix of ifs. Instead of having a series of separate ifs, we can be using the if else structure to check multiple conditions in a single structure. This way, we can make the code more organized and easier to understand.
To create nested conditions using the if else structure, we can apply the following syntax:
if (condition 1) {
if (condition 2) {
// code to be executed if condition 1 is true and condition 2 is true
} else {
// code to be executed if condition 1 is true and condition 2 is false
}
} else {
// code to be executed if condition 1 is false
}
So we can continue adding more nested conditions and creating an inline if else structure.
For example, suppose we want to check if a number is greater than 0 and less than 10, and if it is, we want to check whether it is even or odd. This way, we can use the nested if else structure as follows:
if (number > 0) {
if (number < 10) {
if (number % 2 == 0) {
// code to be executed if number is greater than 0, less than 10 and even
} else {
// code to be executed if number is greater than 0, less than 10 and odd
}
} else {
// code to be executed if number is greater than 0 and greater than or equal to 10
}
} else {
// code to be executed if number equals 0
}
Therefore, the nested if else structure allows us to check multiple conditions in a single structure, making the code more organized and easier to understand. Additionally, it allows us to use different conditions at each level of the framework, and this is useful in situations where we need to check multiple complex conditions.
However, it is important to remember that the nested if else structure can become confusing and difficult to understand if used excessively or without a clear structure. Therefore, it is important to use the framework judiciously and comment the code to make it easier to understand. Furthermore, it is important to remember that there are other ways of structuring the code, such as how we can apply functions and loops, and have more appropriate results in certain situations.
Alternatives to the if else structure in Python
There are several alternatives to the framework if else
in Python for handling conditions and control flows.
And each of these alternatives is useful in different contexts and depending on the specific problem you are looking to solve. It’s important to remember that the structure if else
is a powerful and versatile tool, but there are other ways to deal with conditions in Python. Therefore, choosing the best approach depends on the problem at hand.
Furthermore, it is important to note that alternatives to the framework if else
may be more or less efficient depending on the context. For example, using a dictionary of conditions as we will see below, may be a great way to deal with multiple conditions, but may be less efficient than applying a structure if else
when there are a large number of conditions.
In short, it is important to have different tools and techniques in your programming background, and to know the best ways to deal with conditions in Python, so that we can choose the best solution for the problem in question discussed and analyzed.
Here are some options:
1.Use if
followed by several conditions
if condition1:
# code to be executed if condition1 is true
if condition2:
# code to be executed if condition2 is true
...
Therefore, we can apply this structure when we need a series of conditions and actions associated with each of them.
2. Use if
followed by a list of conditions
if condition1 or condition2 or condition3:
# code to be executed if any of the conditions are true
This way, we apply this structure when we need to check if any of the conditions are true and execute the same code if so.
3. Use if
followed by a dictionary of conditions
conditions = {
'condition1': True,
'condition2': False,
'condition3': True
}
if conditions['condition1']:
# code to be executed if condition1 is true
elif conditions['condition2']:
# code to be executed if condition2 is true
else:
# code to be executed if none of the conditions are true
This way, we apply this framework when we need to check multiple conditions and execute different lines of code based on the conditions.
4. Use try
/ except
to handle exceptions
try:
# code to be executed
except ExceptionType:
# code to be executed if an exception occurs
So, we apply this framework when we need to handle custom exceptions or when we don’t know which exception we can test for.
5. Use assert
to deal with impossible conditions
assert condition, "Error message"
In this sense, we apply this framework when we know that a condition cannot be false and want to handle an error if it does.
6. Use yield
to handle multiple conditions in a single block of code
for condition in conditions:
if condition:
# code to be executed if condition is true
yield
else:
# code to be executed if condition is false
yield
Therefore, we apply this framework when we need to handle multiple conditions in a single block of code and want to execute different chunks of code based on the conditions.
7. Use lambda
to create anonymous functions to handle conditions
conditions = [
lambda: condition1,
lambda: condition2,
lambda: condition3
]
for condition in conditions:
if condition():
# code to be executed if condition is true
break
else:
# code to be executed if condition is false
continues
In this way, we apply this framework when we need to deal with multiple conditions.
8. Use map
to perform a function under various conditions
conditions = [condition1, condition2, condition3]
results = list(map(lambda condition: True if condition else False, conditions))
So, we apply this structure when we need to execute a function under multiple conditions and want a result in a list.
9. Use reduce
to perform a function under various conditions
conditions = [condition1, condition2, condition3]
results = list(reduce(lambda result, condition: result + (True if condition else False), conditions))
In this sense, we apply this structure when we need to execute a function under several conditions and want a result in a list.
10. Use all
to check if all conditions are true
conditions = [condition1, condition2, condition3]
if all(conditions):
# code to be executed if all conditions are true
Thus, we apply this structure when we need to check whether all conditions are true and execute code if so.
11. Use any
to check whether a condition is true
conditions = [condition1, condition2, condition3]
if any(conditions):
# code to be executed if any condition is true
Therefore, we apply this structure when we need to check if some condition is true and execute a code if so.
12. Use sum
to add conditions in a list
conditions = [condition1, condition2, condition3]
results = sum(conditions)
Thus, we apply this structure when we need to add the conditions in a list and want a numerical result.
13. Use account
to perform a function under various conditions
conditions = [condition1, condition2, condition3]
results = list(account(conditions))
Thus, we apply this structure when we need to execute a function under several conditions and want a result in a list.
14. Use itertools.product
to perform a function under various conditions
conditions = [condition1, condition2, condition3]
results = list(itertools.product(conditions))
So we apply this structure when we need to execute a function under multiple conditions and want a result in a list.
15. Use numpy.select
to perform a function under various conditions
conditions = [condition1, condition2, condition3]
results = numpy.select(conditions, [True, True, False])
In this sense, we apply this structure when we execute a function under various conditions and want a numerical result.
Common errors of the if else structure in Python
The if else structure in Python is one of the most used in programming, but it is also one of the most common sources of errors. Here are some of the common errors that can occur when using the if else structure in Python:
- Forgotten Elif Clause: Sometimes we may forget to include an Elif clause, which can lead to unexpected behavior when the condition is not met.
- Incorrect indentation: Indentation is important in Python and incorrect indentation can lead to errors. Therefore, make sure that the if, elif and else clauses are indented correctly.
- Missing Colon: Colon is required after the if and elif clauses. Without a colon, Python will raise a SyntaxError.
- Incorrect condition: Make sure the condition given in the if and elif clauses is correct. A false condition will not be executed, and an incorrect condition can lead to unexpected behavior.
- Nested if statements: Nested if statements can be difficult to read and understand. So, try to avoid using nested if statements and instead use a single if statement with multiple elif clauses.
By being aware of these common errors, we can avoid them in our code and write more reliable and efficient programs.