How to use if-else statements in Python
If-else in Python is a conditional, decision-making statement and a fundamental structure in the programming language. Using a decision-making statement enables the program to execute different blocks of code depending on whether a condition is met at runtime. Keep reading to find out how if statements work in Python.
- Secures data transfers
- Avoids browser warnings
- Improves your Google ranking
What is an if-else statement?
If-else statements are conditional, decision-making statements. You can imagine them like forking train tracks. Depending on which way the switch in the tracks is set, the train will take one of the two tracks. Python is an interpreted language, meaning that an interpreter reads the lines of the source code from top to bottom. In the simplest case, this results in a strictly linear flow — the lines of code are read, interpreted, and executed one after another.
However, this simple case doesn’t allow for more complex programs. Other control structures are needed to achieve the level of variability required for real-world programming. Branching and decision-making statements make it possible to execute some blocks of code only if certain conditions are met. Other control structures include Python for loops and Python while loops, which allow for repetition.
Learn how to program with Python using our Python tutorial!
How do if-else statements work in Python?
Python if-else statements work much like those in other languages. However, there are a couple of key differences. Let’s take a look at how if-else statements work in Python and how they differ from if-else statements in other languages.
General syntax of Python if-else statements
The general syntax of Python if-else statements can be expressed directly in Python code. As shown below, we first define a condition and then specify the function that will be carried out if the condition is met. Then in the else block we specify the code that should be executed if the condition is not met.
if condition:
if_body()
else:
else_body()
The condition can be either true or false. We can make this pattern clearer by directly entering True or False as conditions. This will result in a static program flow in which only one of the two paths will be followed.
if False:
# this code will never be executed
if_body()
else:
else_body()
if True:
if_body()
else:
# this code will never be executed
else_body()
Of course this pattern isn’t useful. We include it only for the sake of illustrating how if-else statements work. In real-world applications, you’ll use an expression for the condition rather than a static True/False value. The expression will be evaluated at the runtime of the program, which will result in a truth value. Depending on whether the truth value is true or false, the program will branch off in one direction or the other.
It’s important to understand that the else part is optional. The code in the else body is only executed if the condition in the if statement isn’t met, and sometimes it’s not necessary to include an else body at all. A Python if statement on its own looks as follows.
if condition:
if_body()
A short note on notation: We’ve been using the words “statement” and “expression” without explaining what they mean. However, it’s important to understand the precise meaning of these words. You’ll also find them used in connection with most other programming languages.
Term | Explanation |
---|---|
Statement | Action that’s executed; influences the flow of the program |
Expression | Term that returns a value when evaluated |
Using elif statements to check for multiple expressions
Elif statements are closely related to Python if statements and can be used to check for the truth of multiple expressions. Elif blocks are added after the if block but before an optional else block. If the condition in the if block is false, the expression in the first elif block will be evaluated. If that is false, the next elif block is evaluated, and so on. An elif statement is only executed if all of the conditions before it were false. That way, only one of the paths of code is followed.
if condition:
if_body()
elif other_condition:
elif_body()
elif another_condition:
another_elif_body()
else:
else_body()
Below is a summary of the rules for how many of the different types of statements can appear.
Statement | How many |
---|---|
if | Exactly one |
elif | None, one, or several |
else | None or one |
How is if-else used in Python?
Like in other programming languages, if statements in Python are a fundamental part of the language. And of course there are a number of different ways to use them. Below we show you some common examples, best practices, and anti-patterns.
Correct use of if statements in Python
First let’s look at how the condition in a decision-making statement works. The condition is interpreted as a Boolean expression that is evaluated and returns a value of True or False. This means you don’t need to explicitly test for equality with a Boolean literal, as is done below.
if expression == True:
...
This won’t result in an error but it will make your code look less professional. Rather than using the above code, an experienced programmer would use the following.
if expression:
...
Let’s take a look at this anti-pattern applied to an example. Let’s say the function is_odd() returns True if a number is odd. Otherwise it returns False.
if is_odd(number) == True:
print("The number is odd.")
So what will happen when the code is executed with an odd number? The expression “is_odd(number) == True” would be evaluated to “True == True”. That would in turn be evaluated to “True”, and the if body would be executed. Perhaps you can see the redundancy involved. It’s much more elegant to cut out “==” and just use the Boolean value returned by the is_odd() function.
if is_odd(number):
print("The number is odd.")
Executing optional code with an if-statement in Python
Let’s imagine that we have a block of code with a certain purpose. The lines are executed one after another. But a certain part of the code should only be executed when a condition is met. To implement this, we only need an if statement. In the code below, we illustrate this using the example of a user signup routine:
def register_user(user_data, do_newsletter_signup = False):
# create user account
user_account = create_account(user_data)
# sign up for newsletter — only if requested by user
if do_newsletter_signup:
signup_newsletter(user_account)
# send confirmation mail
send_confirmation_mail(user_account)
Distinguishing between two cases with if-else in Python
Programs often have to distinguish between two mutually exclusive cases. If according to the rules of logic there can’t be any other possible cases, it makes sense to use an if-else statement. In the example below, we test whether a person has reached a certain age and return the relevant result.
def is_of_age(person, age_limit = 18):
if person.age >= age_limit:
print("You're old enough")
else:
print("Sorry, wait some more")
Distinguishing multiple exclusive cases with elif statements
If you have more than two mutually exclusive cases to distinguish among, elif statements will come in handy. Adding else at the end will serve to catch other cases that are unknown to you when writing the code. In the example below, we assign full names to countries based on their abbreviated country codes.
def get_country_from_code(country_code):
if country_code == 'US':
country = "United States"
elif country_code == 'MX':
country = "Mexico"
elif country_code == 'CA':
country = "Canada"
elif country_code == 'GB':
country = "Great Britain"
elif country_code == 'CN':
country = "China"
else:
country = None
return country
If the elif chain is part of a function, it’s sometimes better to use several independent if statements. That way we can avoid the unnecessary step of assigning values. With the return statement, we exit the function when one of the conditions is true. Rather than “else” at the end, there is a final return statement that’s only reached if none of the conditions was true.
def get_country_from_code(country_code):
if country_code == 'US':
return "United States"
if country_code == 'MX':
return "Mexico"
if country_code == 'CA':
return "Canada"
if country_code == 'GB':
return "Great Britain"
if country_code == 'CN':
return "China"
return None
Chains of elif assignments are a well-known pattern from older languages. In Python, it’s often easier to use a dictionary lookup. We can directly define the assignment of names to country codes and extract the name using the code. Rather than using else at the end, we can use the integrated get method, which takes a default value as its second parameter.
def get_country_from_code(country_code):
countries = {
'US': "United States",
'MX': "Mexico",
'CA': "Canada",
'GB': "Great Britain",
'CN': "China",
}
country = countries.get(country_code, None)
return country
Using an if statement to check if an object contains data
Python is a strongly, dynamically typed language. This means that types are bound on values rather than on variables. Depending on the application, implicit type conversions can take place. In addition to the truth values True and False, there are also the values truthy and falsy.
That means that the condition of an if statement in Python doesn’t need to explicitly evaluate to True or False. Values of other types can also be used as conditions. In that case, they are interpreted as Boolean values using a set of rules.
“Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations […]
[…] An object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero […]” – Source: https://docs.python.org/3/library/stdtypes.html#truth-value-testing
We can make use of this pattern to check whether an object contains any data:
text = ''
if not text:
print("No text given")
The following objects are evaluated to False in a Boolean context and considered “falsy”.
Object | Explanation |
---|---|
False, None | Constants that are defined as False |
0, 0.0, Decimal(0), Fraction(0, 1), etc. | Numbers that represent zero |
'', (), [], {}, set(), range(0), etc. | Empty sequences or collections |
Here’s another example with an empty list:
books_in_library = []
if not books_in_library:
print("Library is empty")
All other objects evaluate to True:
number = 42
if number:
print("Number exists")
Toggling Booleans with if-else in Python
If-else statements can also be used to switch back and forth between two mutually exclusive states. The underlying idea is similar to a light switch. For example, we can define a function that changes the state of a light:
def toggle_light(light):
if light == 'on':
return 'off'
else:
return 'on'
Maybe you’ve already spotted it — there’s an even easier way to do this. If the state is represented as a Boolean value rather than a string, we can do away with the if statement entirely. We’ll use the logical operator NOT instead to negate the truth value of the Boolean:
def toggle(boolean):
return not boolean
Resolving nested if-statements in Python with early return
It’s common practice to execute certain blocks of code when several conditions are true at once. This often leads unexperienced programmers to make nested if-statements. But that kind of nesting is considered bad form, since it makes it harder to follow the code and more arduous to perform maintenance on.
Let’s look at an example. Let’s say we want to define a function that says whether a person is allowed to vote. First we’ll check whether the person has an ID. Then we’ll check whether they are old enough to vote. Here’s how the function would look with nested if-statements:
def person_can_vote(person, voting_age = 18):
if person.has_id():
if person.get_age() >= voting_age:
return True
One big problem with this approach is that the most important part of the code is also the most deeply embedded part. To avoid nested if-statements we can use an early return. With this approach, we check early in the function if the conditions are fulfilled. If one of the conditions is not fulfilled, we’ll exit the function using a return statement.
Let’s reformulate our voting function using early returns. This will often require you to reformulate the conditions in the reverse. Having a basic understanding of Boolean operators in Python will be helpful. If none of the reversed conditions are met, the function will return True.
def person_can_vote(person, voting_age = 18):
if not person.has_id():
return False
if person.age < voting_age:
return False
# if we made it this far, the person can vote
return True
Simplifying and replacing if statements in Python using logical operators
As we saw above, it’s often necessary to test multiple conditions, and it’s preferable to do so without using nested if statements. Let’s take a look at another example involving voting. Using nested if statements, the code would look as follows:
if has_id(person):
if is_adult(person):
print("You may vote")
A more elegant approach to writing this code involves logical operators. Since we want to test whether both conditions are true, we can use the AND operator. Then we’ll only need one if statement.
if has_id(person) and is_adult(person):
print("You may vote")
Here’s an overview of the basic logical operators in Python:
Logical operator | Meaning | Python syntax | Other languages | ||
---|---|---|---|---|---|
AND | Returns true if all conditions are true | and | && | ||
OR | Returns true if at least one of the conditions is true | or | |||
NOT | Reverses the truth value of the expression | not | ! |
Logical operators can also be used to replace if statements entirely, for example when setting default values.
Say there’s a program where the user has the option of choosing a currency for making a purchase. To make the program user-friendly, the setting is optional. If the user doesn’t choose a currency, USD is set as the default value. This can be implemented as follows:
# user didn’t choose a currency
currency = None
...
# further down in the program flow
if not currency:
# set default if value missing
currency = 'USD'
In this case, the logical operator OR can be used in place of an if statement. In the following code, if the user did not choose a currency, the currency variable will be assigned the value “USD”.
# user didn’t choose a currency
currency = None
...
# further down in the program flow
# set default if value missing
currency = currency or 'USD'
What exactly is going on in this code? In the last line, the variable “currency” is assigned a new value. To do this, the expression “currency or ‘USD’” is evaluated. The logical operator OR first evaluates the expression on the left side, in this case “currency”. In this example, currency has the value “None” and thus evaluates to falsy. This means that the expression on the right side will be evaluated (in this case “‘USD’”) and used as a return value for the assignment.
The conditional if-else operator in Python
So far we’ve focused on the decision-making uses of if-else in Python, but if-else can also be used as a conditional operator. It’s called the ternary operator and is used in assignments to distinguish between two possible values.
First let’s look at how this would be done using if-else statements. The code below sets Fahrenheit or Celsius as the unit of temperature, depending on whether the system has been set to metric.
if system == 'metric':
unit = 'C'
else:
unit = 'F'
However, this code can be simplified using the conditional operator:
unit = 'C' if system == 'metric' else 'F'
As its name implies, the ternary operator takes three operands — the two values and an expression giving the condition.
Type of operator | Explanation | Example |
---|---|---|
Unary | Operator takes one operand | not boolean_operand |
Binary | Operator takes two operands | left_operand + right_operand |
Ternary | Operator takes three operands | some_value if condition else other_value |
Replacing if-else in Python with match-case assignment
Match-case statements were introduced with Python version 3.10. They’re akin to switch-case statements in other languages, which are used to terminate long if-elif-else constructions.
Due to their reputation for being prone to error, switch-case statements never made it into Python. Match-case statements in Python are closer to a structural pattern matching functionality borrowed from functional languages like Haskell. Its use far exceeds the scope of switch-case statements.
Below we’ll illustrate the principle behind match case using an example. Say we want to process people’s data in different formats. A person can either be represented just with their name or as a dictionary with their name and age or as a tuple with their first and last name.
# the name 'Jack'
person1 = 'Jack'
# just a name
person2 = 'John'
# name and age in a dict
person3 = {'name': 'Jim', 'age': 42}
# name in a dict, but no age
person4 = {'name': 'Walter', 'email': 'walter.white@example.com'}
# tuple of first and last name
person5 = ('Walter', 'White')
Now let’s take a first stab at a function that greets a person in one of those formats. We’ll use an if-elif-else construction and the isinstance function to distinguish among the various formats. The AND operator will also be used to check for multiple conditions, as will a nested if-else statement. The doesn’t come out particularly clear:
def greet_person(person):
if isinstance(person, str):
if person == 'Jack':
print('Jack himself has arrived')
else:
print(f"Hi there, {person}")
elif isinstance(person, dict) and 'name' in person and 'age' in person:
print(f"It's, {person['name']}. Born {person['age']} years ago")
elif isinstance(person, dict) and 'name' in person:
print(f"It's {person['name']}")
elif isinstance(person, tuple) and len(person) == 2:
first, last = person
print(f"Hello, {first} {last}")
else:
print('Not sure what kind of person this is')
The code will be much more elegant with a match-case statement. The structure of the different formats can be described directly, and individual values can be extracted as variables. The code comes out much more clear, less complex and easier to follow:
def match_person(person):
match person:
case 'Jack':
print('Jack himself has arrived')
case str() as name:
print(f"Hi there, {name}")
case {'name': name, 'age': age}:
print(f"It's, {name}. Born {age} years ago")
case {'name': name}:
print(f"It's {name}")
case (first, last):
print(f"Hello, {first} {last}")
case _:
print('Not sure what kind of person this is')