Python if Statement (if, elif, else)

Modified: | Tags: Python

This article explains the basic syntax of Python's if statement (if ... elif ... else ...), including how to specify multiple conditions and negated conditions.

Python also provides a ternary operator for writing single-line conditional branching. See the following article for more information.

Python if statement syntax: if, elif, else

The basic structure of a Python if statement is as follows.

if condition_1:
    # Execute if condition_1 is true
elif condition_2:
    # Execute if condition_1 is false and condition_2 is true
elif condition_3:
    # Execute if condition_1 and condition_2 are false, and condition_3 is true
...
else:
    # Execute if all preceding conditions are false

In Python, blocks are expressed with indentation (usually four spaces) rather than brackets.

In the following examples, the def statement is used to define functions, and f-strings are used to embed variables into strings.

if

In the case of if only, the specified process is executed if the condition evaluates to true, and nothing is done if it evaluates to false.

def if_only(n):
    if n > 0:
        print(f'{n} is positive')

if_only(100)
# 100 is positive

if_only(-100)
source: if_basic.py

It is not necessary to enclose the condition in parentheses (), but doing so will not cause an error.

Although the example shows the process inside the block as only one line, you can write a multi-line process as well.

if ... else ...

The else clause allows you to add a process for when the condition evaluates to false.

def if_else(n):
    if n > 0:
        print(f'{n} is positive')
    else:
        print(f'{n} is negative or zero')

if_else(100)
# 100 is positive

if_else(-100)
# -100 is negative or zero
source: if_basic.py

if ... elif ...

The elif clause allows you to add processes for different conditions. elif corresponds to else if or elseif in other programming languages and can be used multiple times.

Conditions are checked in order from the top, and the block with the first condition determined to be true is executed. Nothing is done if all conditions are false.

def if_elif(n):
    if n > 0:
        print(f'{n} is positive')
    elif n == 0:
        print(f'{n} is zero')
    elif n == -1:
        print(f'{n} is minus one')

if_elif(100)
# 100 is positive

if_elif(0)
# 0 is zero

if_elif(-1)
# -1 is minus one

if_elif(-100)
source: if_basic.py

As described later, you can also specify a combination of multiple conditions in a single expression using and or or.

if ... elif ... else ...

The elif and else clauses can be used together in the same conditional branching structure. Note that else must be the last clause.

The process in the else clause is executed if all preceding conditions evaluate as false.

def if_elif_else(n):
    if n > 0:
        print(f'{n} is positive')
    elif n == 0:
        print(f'{n} is zero')
    else:
        print(f'{n} is negative')

if_elif_else(100)
# 100 is positive

if_elif_else(0)
# 0 is zero

if_elif_else(-100)
# -100 is negative
source: if_basic.py

Conditions in if statements

Expressions that return bool (comparison operators, in operator, etc.)

You can use expressions that return bool values (True or False) in if statement conditions. Comparison operators are typical examples of such expressions.

Python has the following comparison operators:

Operator Result
x < y True if x is less than y
x <= y True if x is less than or equal to y
x > y True if x is greater than y
x >= y True if x is greater than or equal to y
x == y True if x is equal to y
x != y True if x is not equal to y
x is y True if x and y are the same object
x is not y True if x and y are not the same object

See the following article for the difference between == and is.

Python also allows chaining of comparison operators, such as a < x < b.

You may also use in and not in to check whether a list or string contains a specific element or substring.

def if_in(s):
    if 'a' in s:
        print(f'"a" is in "{s}"')
    else:
        print(f'"a" is not in "{s}"')

if_in('apple')
# "a" is in "apple"

if_in('cherry')
# "a" is not in "cherry"
source: if_basic.py

You can also specify methods or functions that return bool as a condition in the if statement. For example, the startswith() method checks if a string starts with a specific substring.

def if_startswith(s):
    if s.startswith('a'):
        print(f'"{s}" starts with "a"')
    else:
        print(f'"{s}" does not start with "a"')

if_startswith("apple")
# "apple" starts with "a"

if_startswith("banana")
# "banana" does not start with "a"
source: if_basic.py

Non-bool cases

You can use non-bool values, such as numbers or lists, and expressions that return those values as if statement conditions.

if 100:
    print('True')
# True

if [0, 1, 2]:
    print('True')
# True
source: if_basic.py

In Python, the following objects are considered false:

Numeric values representing zero, as well as empty strings and empty lists, are considered false, while all other values are considered true.

This can be used to write simple conditions, such as checking if a list is empty, without retrieving the number of elements.

def if_is_empty(l):
    if l:
        print(f'{l} is not empty')
    else:
        print(f'{l} is empty')

if_is_empty([0, 1, 2])
# [0, 1, 2] is not empty

if_is_empty([])
# [] is empty
source: if_basic.py

Remember, non-empty strings, including 'False', are considered true. To convert specific strings such as 'True' or 'False' to 1 or 0, you can use the distutils.util.strtobool() function. See the following article for more information.

Multiple conditions in if statements: and, or

To combine multiple conditions in an if statement using logical AND or OR, employ the and or or operators, respectively.

def if_and(n):
    if n > 0 and n % 2 == 0:
        print(f'{n} is positive-even')
    else:
        print(f'{n} is not positive-even')

if_and(10)
# 10 is positive-even

if_and(5)
# 5 is not positive-even

if_and(-10)
# -10 is not positive-even
source: if_basic.py

You can use and or or multiple times in a single expression.

def if_and_or(n):
    if n > 0 and n % 2 == 0 or n == 0:
        print(f'{n} is positive-even or zero')
    else:
        print(f'{n} is not positive-even or zero')

if_and_or(10)
# 10 is positive-even or zero

if_and_or(5)
# 5 is not positive-even or zero

if_and_or(0)
# 0 is positive-even or zero
source: if_basic.py

The order of precedence for Boolean operators is not > and > or (with not being the highest). For more details, see the following article.

Negation in if statements: not

To specify the negation (NOT) in an if statement, use the not operator.

def if_not(s):
    if not s.startswith('a'):
        print(f'"{s}" does not start with "a"')
    else:
        print(f'"{s}" starts with "a"')

if_not("apple")
# "apple" starts with "a"

if_not("banana")
# "banana" does not start with "a"
source: if_basic.py

However, for operators such as == or >, it is recommended to use their opposite counterparts directly, like != or <=, rather than not.

How to write a condition across multiple lines

For long conditions using and or or, you can break them into multiple lines using a backslash \ or enclosing the entire expression in parentheses ().

Although written differently, the following three functions are equivalent.

def if_no_newline():
    if too_long_name_function_1() and too_long_name_function_2() and too_long_name_function_3():
        print('True')
    else:
        print('False')
source: if_basic.py
def if_backslash():
    if too_long_name_function_1() \
       and too_long_name_function_2() \
       and too_long_name_function_3():
        print('True')
    else:
        print('False')
source: if_basic.py
def if_parentheses():
    if (
        too_long_name_function_1()
        and too_long_name_function_2()
        and too_long_name_function_3()
    ):
        print('True')
    else:
        print('False')
source: if_basic.py

You can break lines as many times as needed using backslash \ or parentheses (), without indentation restrictions. This technique can be used anywhere in Python code, not just in if statements.

Related Categories

Related Articles