TheDeveloperBlog.com


Python If Examples: Elif, Else

Python If Examples: Elif, Else

If-statements. A selection statement changes the flow of control. It acts upon a value. The if-statement in Python is a core selection statement. We use "if" to make a choice.


We can compare anything: numbers, strings, booleans, method results. With keywords (and, not, or) we modify the expressions within an if.


An example. An if-statement can be followed by an elif-statement and an else-statement. The elif and else parts are optional. The if can stand alone and have no elif or else.

If: This is followed by a colon character. Its expression is evaluated to true or false.

Elif: This is the same as if, but it must come after if and before else. It can come at the end.

Else: It must come at the end. It has no expression to evaluate. It is executed when if and elif evaluate to false.

Based on:

Python 3

Python program that uses if-statements

def test(n):
    if n == 0:
        print("None")
    elif n < 0:
        print("Low")
    else:
        # Handle values greater than zero.
        if n > 100:
            print("Out of range")
        else:
            print("High")

test(-1)
test(0)
test(1)
test(1000)

Output

Low
None
High
Out of range

Indentation. In the above method test(), we have four spaces of indentation before all the statements inside. And the block of code within the else has an additional four spaces.

Note: All the blocks of code within if, elif and else scopes must have an additional level of indentation.


Same line. An if-statement can be on the same line as its body. This only works if there is one only statement in the body. A syntax error occurs otherwise.

Often: Indenting the statements, as in this example, is visually helpful. This improves readability.

Tip: You can mix same-line statements with multiple-line blocks in the same if-else chain. The goal is easy-to-read code.

Python program that uses same-line if

# A variable.
a = 1

# Test variable.
if a == 1:   print("1")
elif a == 2: print("2")

Output

1

In keyword. Collections such as dictionaries can be used with the if-statement. With a dictionary, the in keyword is used in an if-statement. We test the collection for a key's existence.

In
Python program that uses if with dictionary

birds = {"parakeet": 1, "parrot": 2}

if "parrot" in birds:
    print("Found")

Output

Found

And, or. The && and || operators are not available in Python. We use instead the "and" and "or" keywords. This syntax is easier to read. We can use parentheses to form expressions.

Note: These if-statements have expressions that use "and" or "or." They all evaluate to true, and the inner print statements are reached.

Tip: Expressions can be even more complex. And you can call methods and use them instead of variables.

Tip 2: If-statements can also be nested. And sometimes it is possible to change complex expressions into a simpler if-else chain.

Python program that uses logical operators

a = 1
b = 2

if a == 1 and b == 2:
    print(True)

if a == 0 or b == 2:
    print(True)

if not (a == 1 and b == 3):
    print(True)

if a != 0 and b != 3:
    print(True)

Output

True
True
True
True

Not keyword. This is used in ifs. It causes false expressions to evaluate to true ones. It comes before some expressions, but for "in" expressions, we use the "not in" construct.

Caution: For the first example of "not" here, I recommend instead using the != operator. This style is more familiar to many programmers.

Python program that uses not

number = 1

# See if number is not equal to 2.
if not number == 2:
    print("True")

birds = {"cormorant" : 1, "cardinal" : 2}

# See if string not in collection.
if "automobile" not in birds:
    print("Not found")

Output

True
Not found

Store expressions. If-statements can become complex. Often repetition is at fault. The same variables, in the same expressions, are tested many times.

Result: We can store the result of an expression in a variable. Then, we test the variable.

Tip: This reduces repetition. It may also improve processing speed: fewer comparisons are done.

Here: We store the result of an expression in the "all" variable. We then test it twice.

Python program that stores expression result, variable

a = 1
b = 2
c = 3

# Store result in expression.
all = a == 1 and b == 2 and c == 3

# Test variable.
if all:
    print(1)

# Use it again.
if all:
    print(2)

Output

1
2

Tuple. The if-statement is helpful with a tuple. In this example, we use a tuple directly inside the if-statement. The method test() prints "Match" if its argument is 0, 2 or 4.

Tuple
Python that uses tuple, if-statement

def test(x):
    # Test x with tuple syntax.
    if x in (0, 2, 4):
        print("Match")
    else:
        print("Nope")

test(0)
test(1)
test(2)

Output

Match   x = 0
Nope    x = 1
Match   x = 2

Truth. Let us consider the truth of things. Python considers some values True, in an if-statement, and others false. The "None" value is False, and a class instance is True.

Negative 1: This evaluates to True. Nonzero numbers, like -1 and 1 are considered True.

Zero: This is False. Zero is the only False integer—all others, negative and positive, are considered True.

None: This is also False. Many methods return None when they find no answer. We can directly test these in an if.

None

Class: A Class instance is considered True. So if we test a new class instance, we will enter the if-block.

Empty list: The [] characters denote an empty list. Python evaluates zero-element collections to False.

Python that tests values for true or false

# An empty class for testing.
class Box:
    pass

# Some values to test.
values = [-1, 0, 1, None, Box(), []]

# See if the values are treated as "true" or "false".
for value in values:
    if value: print("True ", end="")
    else: print("False", end="")

    # Display value.
    print("... ", value)

Output

True ...  -1
False...  0
True ...  1
False...  None
True ...  <__main__.Box object at 0x01984f50>
False...  []

True, False. Programs can always access the True and False constants. We can use True and False in ifs to make our logic clearer. This code makes explicit what value we are comparing.

Python that uses True, False

value1 = 10
value2 = 10

# See if these two values are equal.
equal = value1 == value2

# Test True and False constants.
if equal == True: print(1)
if equal != False: print(2)

Output

1
2

Method. Often we test variables directly in if-statements. But we can test the result of methods. This can simplify complex logic. Here, we invoke result() in if-statements.

Caution: For predicate methods, where a truth value is returned, side effects (like a field assignment) can lead to confusing code.

Python that uses method in if

def result(a):
    if a == 10:
        return True

# Use method in an if-statement condition.
if result(10):
    print("A")

if not result(5):
    print("B")

Output

A
B

Is-keyword. This tests identity. Every object (like integers, classes) has an id. When the ids of two objects are equal, their identities too are equal. And the is-test will return True.

The operators "is" and "is not" test for object identity: "x is y" is true if and only if "x" and "y" are the same object. Python help

Python that uses is

class Bird:
    pass

# Create two separate objects.
owl = Bird()
parrot = Bird()

# The objects are not identical.
if owl is not parrot:
    print(False, id(owl), id(parrot))

# These objects are identical.
copy = owl
if copy is owl:
    print(True, id(copy), id(owl))

Output

False 4353337736 4353337792
True 4353337736 4353337736

SyntaxError. When comparing two values in an if-statement, two equals signs are required. Python reports a compile-time error when only one is found. One equals sign means an assignment.

Note: The programs with this problem can never be executed. This is helpful: it prevents invalid programs from causing a headache.

Python that causes SyntaxError

value = 100

# This should have two equals signs!
if value = 1000:
    print(True)

Output

  File "C:\programs\file.py", line 6
    if value = 1000:
            ^
SyntaxError: invalid syntax

Reorder. The and-operator short-circuits. This means when a sub-expression evaluates to false, no further ones are evaluated. We can exploit this principle to improve speed.

Here: A list contains four sub-lists. In the value pairs, the first element differs most: there are three unique first numbers.

Value 2: This is always 1 in the pairs. It is least specific when checking the pairs.

So: To find pairs with both values set to 1, we should first check the most specific value—the first one.

Python that optimizes if-checks

values = [[1, 1], [2, 1], [1, 1], [3, 1]]

for pair in values:
    # We test the first part of each list first.
    # ... It is most specific.
    # ... This reduces total checks.
    if pair[0] == 1 and pair[1] == 1:
        print(True)

Output

True
True

Benchmark. If-statements can be written in many ways. We test an if that checks a variable against a tuple of three values. We then time an if-elif construct that does the same thing.

Result: The syntax that uses (1, 2, 3) was faster than the form that uses if and two elifs. The tuple-style syntax is efficient.

Python that benchmarks if, tuple

import time

print(time.time())

# Version that uses tuple.
v = 0
i = 0
x = 2

while i < 10000000:
    if x in (1, 2, 3):
        v += 1
    i += 1

print(time.time())

# Version that uses if-elif.
v = 0
i = 0
while i < 10000000:
    if x == 1:
        v += 1
    elif x == 2:
        v += 1
    elif x == 3:
        v += 1
    i += 1

print(time.time())

Output

1361579543.768
1361579547.067    Tuple syntax = 3.23 s
1361579550.634    If-elif      = 3.57 s

Control flow is a key concept in programs. Constructs such as loops and the if-statement manipulate control flow inside methods. And methods themselves influence flow outside this scope.


A review. The if, elif and else-statements are used in nearly every program. The else-statement is used with loop constructs. If a loop never iterates once, the else is reached.