If-else in Python is a con­di­tion­al, decision-making statement and a fun­da­men­tal structure in the pro­gram­ming 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 state­ments work in Python.

Be secure. Buy an SSL cer­tifi­cate.
  • Secures data transfers
  • Avoids browser warnings
  • Improves your Google ranking

What is an if-else statement?

If-else state­ments are con­di­tion­al, decision-making state­ments. 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 in­ter­pret­ed language, meaning that an in­ter­preter 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, in­ter­pret­ed, and executed one after another.

However, this simple case doesn’t allow for more complex programs. Other control struc­tures are needed to achieve the level of vari­abil­i­ty required for real-world pro­gram­ming. Branching and decision-making state­ments make it possible to execute some blocks of code only if certain con­di­tions are met. Other control struc­tures include Python for loops and Python while loops, which allow for rep­e­ti­tion.

Tip

Learn how to program with Python using our Python tutorial!

How do if-else state­ments work in Python?

Python if-else state­ments work much like those in other languages. However, there are a couple of key dif­fer­ences. Let’s take a look at how if-else state­ments work in Python and how they differ from if-else state­ments in other languages.

General syntax of Python if-else state­ments

The general syntax of Python if-else state­ments 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 con­di­tions. 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 il­lus­trat­ing how if-else state­ments work. In real-world ap­pli­ca­tions, you’ll use an ex­pres­sion for the condition rather than a static True/False value. The ex­pres­sion 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 un­der­stand 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 “ex­pres­sion” without ex­plain­ing what they mean. However, it’s important to un­der­stand the precise meaning of these words. You’ll also find them used in con­nec­tion with most other pro­gram­ming languages.

Term Ex­pla­na­tion
Statement Action that’s executed; in­flu­ences the flow of the program
Ex­pres­sion Term that returns a value when evaluated

Using elif state­ments to check for multiple ex­pres­sions

Elif state­ments are closely related to Python if state­ments and can be used to check for the truth of multiple ex­pres­sions. Elif blocks are added after the if block but before an optional else block. If the condition in the if block is false, the ex­pres­sion 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 con­di­tions 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 state­ments 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 pro­gram­ming languages, if state­ments in Python are a fun­da­men­tal 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 state­ments in Python

First let’s look at how the condition in a decision-making statement works. The condition is in­ter­pret­ed as a Boolean ex­pres­sion that is evaluated and returns a value of True or False. This means you don’t need to ex­plic­it­ly 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 pro­fes­sion­al. Rather than using the above code, an ex­pe­ri­enced pro­gram­mer 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 ex­pres­sion “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 re­dun­dan­cy 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 il­lus­trate 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)

Dis­tin­guish­ing between two cases with if-else in Python

Programs often have to dis­tin­guish 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")

Dis­tin­guish­ing multiple exclusive cases with elif state­ments

If you have more than two mutually exclusive cases to dis­tin­guish among, elif state­ments 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 ab­bre­vi­at­ed 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 in­de­pen­dent if state­ments. That way we can avoid the un­nec­es­sary step of assigning values. With the return statement, we exit the function when one of the con­di­tions is true. Rather than “else” at the end, there is a final return statement that’s only reached if none of the con­di­tions 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 as­sign­ments are a well-known pattern from older languages. In Python, it’s often easier to use a dic­tio­nary lookup. We can directly define the as­sign­ment of names to country codes and extract the name using the code. Rather than using else at the end, we can use the in­te­grat­ed 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, dy­nam­i­cal­ly typed language. This means that types are bound on values rather than on variables. Depending on the ap­pli­ca­tion, implicit type con­ver­sions 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 ex­plic­it­ly evaluate to True or False. Values of other types can also be used as con­di­tions. In that case, they are in­ter­pret­ed as Boolean values using a set of rules.

Quote

“Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean op­er­a­tions […]
[…] An object is con­sid­ered 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 con­sid­ered “falsy”.

Object Ex­pla­na­tion
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 col­lec­tions

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 state­ments can also be used to switch back and forth between two mutually exclusive states. The un­der­ly­ing 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 rep­re­sent­ed 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-state­ments in Python with early return

It’s common practice to execute certain blocks of code when several con­di­tions are true at once. This often leads un­ex­pe­ri­enced pro­gram­mers to make nested if-state­ments. But that kind of nesting is con­sid­ered bad form, since it makes it harder to follow the code and more arduous to perform main­te­nance 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-state­ments:

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-state­ments we can use an early return. With this approach, we check early in the function if the con­di­tions are fulfilled. If one of the con­di­tions is not fulfilled, we’ll exit the function using a return statement.

Let’s re­for­mu­late our voting function using early returns. This will often require you to re­for­mu­late the con­di­tions in the reverse. Having a basic un­der­stand­ing of Boolean operators in Python will be helpful. If none of the reversed con­di­tions 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

Sim­pli­fy­ing and replacing if state­ments in Python using logical operators

As we saw above, it’s often necessary to test multiple con­di­tions, and it’s prefer­able to do so without using nested if state­ments. Let’s take a look at another example involving voting. Using nested if state­ments, 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 con­di­tions 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 con­di­tions are true and &&
OR Returns true if at least one of the con­di­tions is true or
NOT Reverses the truth value of the ex­pres­sion not !

Logical operators can also be used to replace if state­ments 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 im­ple­ment­ed 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 ex­pres­sion “currency or ‘USD’” is evaluated. The logical operator OR first evaluates the ex­pres­sion 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 ex­pres­sion on the right side will be evaluated (in this case “‘USD’”) and used as a return value for the as­sign­ment.

The con­di­tion­al 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 con­di­tion­al operator. It’s called the ternary operator and is used in as­sign­ments to dis­tin­guish between two possible values.

First let’s look at how this would be done using if-else state­ments. The code below sets Fahren­heit or Celsius as the unit of tem­per­a­ture, depending on whether the system has been set to metric.

if system == 'metric':
    unit = 'C'
else:
    unit = 'F'

However, this code can be sim­pli­fied using the con­di­tion­al operator:

unit = 'C' if system == 'metric' else 'F'

As its name implies, the ternary operator takes three operands ⁠— the two values and an ex­pres­sion giving the condition.

Type of operator Ex­pla­na­tion 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 as­sign­ment

Match-case state­ments were in­tro­duced with Python version 3.10. They’re akin to switch-case state­ments in other languages, which are used to terminate long if-elif-else con­struc­tions.

Due to their rep­u­ta­tion for being prone to error, switch-case state­ments never made it into Python. Match-case state­ments in Python are closer to a struc­tur­al pattern matching func­tion­al­i­ty borrowed from func­tion­al languages like Haskell. Its use far exceeds the scope of switch-case state­ments.

Below we’ll il­lus­trate the principle behind match case using an example. Say we want to process people’s data in different formats. A person can either be rep­re­sent­ed just with their name or as a dic­tio­nary 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 con­struc­tion and the isin­stance function to dis­tin­guish among the various formats. The AND operator will also be used to check for multiple con­di­tions, as will a nested if-else statement. The doesn’t come out par­tic­u­lar­ly 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 in­di­vid­ual 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')
Go to Main Menu