# 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.

Let's jump right in.

## 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

We’ve discussed conditional comparison operators before, but we provide a quick recap below.

The following table lists the comparison operators we use with conditional logic:

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. If the result returns True, the code in the code block will execute.

We write an if statement by using the if keyword. Then, we write our comparison expression, followed by a colon operator.

On the next line(s) we write the execution code, otherwise known as a code block, with a single indentation.

Syntax:
``````if comparison:
execution code``````
Example: If condition evaluates to True
``````a, b = 2, 1

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

In the example above, we evaluate if the value of “a” is greater than the value of “b”. It is, so we execute the print() statement.

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

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

In the example above, we evaluate if the value of “a” is equal to the value of “b”. It isn’t, so nothing will happen. The interpreter didn’t have permission to execute the print() statement.

##### 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(s), 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 operator, but there isn’t one.

##### The elif (elseif) conditional statement

When the condition of our if statement is not met, we have the option to try other conditions.   We write an elif statement in the same way as an if statement, except for the elif keyword.

Syntax:
``````if condition:
execution code
elif condition:
execution code``````
``````a = 15

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

In the example above, we simulated input from a user, stored in the variable “a”.

The conditional logic starts at the if statement. If the condition is not met, the interpreter will move on to the elif statement(s).

##### The else conditional statement

The else statement is a fallback to catch anything that isn’t handled by the if and elif statements.

We write the else statement with the keyword else , and without any conditions.

Syntax:
``````if condition:
execution code
elif condition:
execution code
else:
execution code``````
Example: If condition evaluates False, catchall with else
``````a = 15

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

In the example above, we don’t help the user narrow their search for the mystery number. We don’t specify through elif statements that they guessed above or below the number.

We catch anything that isn’t the mystery number with an else statement.

## Conditional And, Or

In Python we can test multiple conditions in one if, or elif, statement.

##### Conditional AND

We can evaluate when multiple if conditions are true with the and keyword. All the conditions in the expression must evaluate to true.

If one or more of the conditions evaluate to false, the code block will not execute.

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

##### Conditional OR

We can also evaluate if one of multiple conditions is true with the or keyword. Only one of the conditions in the expression must evaluate to true for the code block to execute.

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")``````

## Conditional shorthand and the Ternary operator

Python allows us to put an if/elif/else 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 if/else 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:
`` if 1 == 1: print("Inline")``
##### The if / else ternary operator

As mentioned earlier, the ternary operator syntax is different from a normal inline if/else statement.

Consider the following ternary syntax example.

Example: Ternary operator
`` x if C else y``

First, we evaluate condition C. Then, if the condition is met, 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
`` print('if execution') if 1==1 else print('else execution')``

In the example above, we print the message “if execution” if the ternary condition evaluates to true (which it does), else we print the message “else execution”.

The ternary operator is used for if/else 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.
• if, elif, and else statements are used with conditions and conditional operators, like ==.
• Instead of curly braces, we define scope for conditional statements with a line break and one or more indentations.
• If and elif require a 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 if statement on one line.
• The ternary operator is a shorthand method of writing an if/else statement.