Python if, elif, else & ternary Conditional Control Flow Tutorial

In this tutorial we learn how to control the flow of an application through conditional logic with if, elif and else conditional statements.

What is Conditional Control Flow?

Python allows us to control the flow of our application through conditional logic, like those used in mathematics.

We evaluate conditional expressions and, based on the result, execute code statements.

Conditional Comparison Operators

Because we’ll be using conditional comparison operators, let’s quickly go over them again below.

OperatorDescription
==If the values of the two operands match, the condition is true
!=If the values of the two operands do not match, the condition becomes true
<If the first operand is less than the second operand, the condition becomes true
>If the first operand is greater than the second operand, the condition becomes true
<=If the first operand is less than or matches the second operand, the condition becomes true
>=If the first operand is greater than or matches the second operand, the condition becomes true

Conditional Statements

We can use the comparison operators above with conditional statements.

The following table lists the conditional statements available to us in Python:

StatementDescription
ifExecute code only if we receive the desired result from the comparison operator(s)
elifSimilar to if, but used as secondary, tertiary, etc. Tests with different comparison logic
elseIf none of the above code executes, fall back to the else code

The conditional statements above also come in shorthand flavor, discussed further below.

The if conditional statement

An if statement will evaluate a conditional expression and execute code we specify based on the result.

We start the statement with the if keyword, followed by a condition and a : (colon). On the next line we write the execution code (known as a code block) with a single indentation.

Syntax:
if comparison:
    # execution code

If the condition evaluates to true, the code in the code block will be executed. If the condition evaluates to false, the interpreter will move on to code outside and below the if statement.

As an example, let’s compare the two numbers and ensure that the condition will return true.

Example: If condition evaluates to True
a, b = 2, 1

if a > b:
    print(f"{a} is greater than {b}")

Because the value of “a” is greater than the value of “b”, the condition evaluates to true and the print statement is executed.

Now let’s ensure the condition returns false.

Example: If condition evaluates False
a, b = 2, 1

if a == b:
    print(f"{a} is equal to {b}")

This time, the condition will evaluate to false so the interpreter won’t have permission to execute the print statement and nothing will happen.

Indentation to define scope

In Python, a code block must be indented because Python doesn’t use the curly braces to define scope.

If we don’t indent the code block statement, the interpreter will raise an error.

Example: Non-indented if statement
a, b = 2, 1

if a > b:
print(f"{a} is greater than {b}")

From the example above, we’ll receive an IndentationError.

Output:
 IndentationError: expected an indented block

The interpreter expected an indent after the colon, but there isn’t one so it raises an error.

The elif (elseif) conditional statement

When the condition of our if statement is not met, we have the option to try other conditions by using the elif statement.

tip Python allows more than one elif statement.

Syntax: elif
if condition:
    # execution code
elif condition:
    # execution code
elif condition:
    # execution code

If the if condition fails, the interpreter will move on to subsequent elif conditions.

If one of the elif conditions in the ladder prove true, the interpreter will execute its code block and move on to any code outside and below the entire block of statements.

As an example, let’s simulate a number guessing game.

Example: elif ladder
guess = 15

if guess == 10:
    print("Correct, the mystery number is 10")
elif guess > 10:
    print("You guessed too high, try again")
elif guess < 10:
    print("You guessed too low, try again")

Because the guess in the example above is 15, the interpreter will stop at the first elif statement and execute its code.

note An elif statement can only be chained to an if statement, it can’t stand on its own.

The else conditional statement

The else statement is a fallback to catch anything that isn’t handled by the others. And because it acts as a catch-all, it doesn’t have a condition.

Syntax:
if condition:
    # execution code
elif condition:
    # execution code
else:
    # execution code

To demonstrate, let’s change our earlier guessing game to not give the user any hints. Instead, we’ll catch anything that isn’t the correct number with an else statement.

Example: If condition evaluates False, catchall with else
guess = 15

if guess == 10:
    print("Correct, the mystery number is 10")
else:
    print("Sorry, that is not the mystery number. Try again")

Because the guess is wrong in the example above, the else will catch it and print its message to the console.

note An else statement can only be chained to an if or elif statement, it can’t stand on its own.

Conditional And, Or

Python allows us to test multiple conditions in a single if or elif statement with and and or .

Conditional AND

When we want to test if more than one condition is true, we separate them with the and keyword.

Example: Both expressions evaluate to true
ammo = 14
max_ammo = 15
reloading = True

if ammo != max_ammo and reloading is True:
    print("Cover me I'm reloading!")

note All conditions must prove true, otherwise the code block won’t execute.

Conditional OR

When we want to test if one condition out of many are true, we separate them with the or keyword.

Example: One condition evaluates true
birthday = False
hungry = True

if birthday is True or hungry is True:
    print("I think I'll have some cake")

note Only one of the conditions must prove true.

Inline if/else statements and the Ternary operator

Python allows us to put a conditional statement on one line with the ternary operator, or by simply writing it on a single line.

The ternary operator uses a different syntax structure than a normal inline conditional statement.

Let’s look at the simpler inline statement first, before moving on to the ternary operator.

Regular inline if statement

If we only have a single execution statement, we can write it on the same line as the if statement.

Example: inline
 if 1 == 1: print("Inline")

The if/else ternary operator

The ternary operator acts as a shorthand method of writing simple conditional statements.

Python’s ternary operator seems a little confusing at first, especially for developers used to other languages. So let’s start with the syntax, then explain what’s happening.

Syntax: Ternary operator
# ternary operator
x if C else y


# traditional if/else
if C:
    execute x
else:
    execute y

The condition we want to evaluate (in this case C), is written in the middle of the ternary. If the condition proves true, execute whatever the x expression is, otherwise execute y.

The statement reads: do x if C condition is true, else do y

Example: Ternary operator
# this traditional if/else
if 1==1:
    print("if execution")
else:
    print("else execution")


# converts to this ternary
print("if execution") if 1==1 else print("else execution")

note The ternary operator is used for conditional statements that only contain a single if and a single else execution statement.

It should also be noted that the ternary operator is considered un-Pythonic, especially for programmers that aren’t used to the C language.

In most cases it’s better to keep the code easily readable instead of short. When in doubt, don’t use the ternary operator.

Summary: Points to remember

  • if , elif and else statements allow us to control the flow of our application with conditions.
  • Conditions use conditional operators like == for testing.
  • Instead of curly braces, we define scope for conditional statements with a line break and one or more indentations.
  • if and elif require execution blocks, else does not.
  • We can test for two or more conditions with and .
  • We can test for either conditions with or .
  • If an execution block only has one statement, we can write the whole statement on one line.
  • The ternary operator is a shorthand method of writing a conditional statement.