How to write conditional branches with if statements in Python

Money and Business

Explain conditional branching with if statements in Python.

  • Basics of if statements (if, elif, else)
  • Specify conditions with comparison operators, etc.
  • Specify conditions by number, list, etc.
  • Specify multiple conditions or negations with logical operators (and, or, not)
  • Conditional expressions on new lines and multiple lines

There is also a ternary operator that describes a conditional branch in one line. See the following article.

Basics of if statements (if, elif, else)

The basic form of the if statement is as follows

if Conditional expression 1:
    `Processing to be performed if Expression 1 is True.`
elif Conditional expression 2:
    `Processing to be performed when expression 1 is false and expression 2 is true.`
elif Expression 3:
    `Process when expression 1 and 2 are false and expression 3 is true.`
...
else:
    `Processing when all conditionals are false.`

The “elif” corresponds to the “else if” in C and other languages, and there may be any number of “elifs”.

If there is only one conditional expression or processing when false is not necessary, the “elif” and “else” blocks can be omitted.

Specify conditions with comparison operators, etc.

Specify the condition with an operation that returns a bool type (true, false), such as a comparison operator.

Python comparison operators are as follows

operatorresult
x < ytrue if x is less than y
x <= ytrue if x is less than or equal to y
x > ytrue if x is greater than y
x >= ytrue if x is greater than or equal to y
x == ytrue if x and y values are equal
x != ytrue if x and y values are not equalx is ytrue if x and y are the same objectx is not ytrue if x and y are not the same objectx in ytrue if x is contained in yx not in ytrue if x is not contained in y

Example. For convenience, it is defined as a function with the def statement.

def if_test(num):
    if num > 100:
        print('100 < num')
    elif num > 50:
        print('50 < num <= 100')
    elif num > 0:
        print('0 < num <= 50')
    elif num == 0:
        print('num == 0')
    else:
        print('num < 0')

if_test(1000)
# 100 < num

if_test(70)
# 50 < num <= 100

if_test(0)
# num == 0

if_test(-100)
# num < 0

The following can be written in a way that is unique to Python. See the following article for details.
a < x < b

def if_test2(num):
    if 50 < num < 100:
        print('50 < num < 100')
    else:
        print('num <= 50 or num >= 100')

if_test2(70)
# 50 < num < 100

if_test2(0)
# num <= 50 or num >= 100
  • ==
  • !=

The above is a comparison of values; to compare object identities, use the following

  • is
  • is not

For example, when comparing an integer and a floating-point number, “==” returns true if the values are equivalent, but “is” returns false because they are different objects.

i = 10
print(type(i))
# <class 'int'>

f = 10.0
print(type(f))
# <class 'float'>

print(i == f)
# True

print(i is f)
# False

It is also possible to make the condition whether a list or a string contains a specific element (character).

  • in:include
  • not in:not including
def if_test_in(s):
    if 'a' in s:
        print('a is in string')
    else:
        print('a is NOT in string')

if_test_in('apple')
# a is in string

if_test_in('melon')
# a is NOT in string

Specify conditions by number, list, etc.

The conditional expression of an if statement can be a number, list, or other object that is not of type bool (true, false).

if 10:
    print('True')
# True

if [0, 1, 2]:
    print('True')
# True

In the conditional expression of a Python if statement, the following objects are considered false.

Numbers representing zero, empty strings, lists, etc. are considered false; all others are considered true.

How the object is judged can be checked with bool().

print(bool(10))
# True

print(bool(0.0))
# False

print(bool([]))
# False

print(bool('False'))
# True

This can be used to simply write the process when the list is empty, for example.

def if_test_list(l):
    if l:
        print('list is NOT empty')
    else:
        print('list is empty')

if_test_list([0, 1, 2])
# list is NOT empty

if_test_list([])
# list is empty

Note that the string 'False' will also be true, because as shown in the example above, any string that is not empty in the string will be true.' To convert a specific string such as 'True' or 'False' to 1,0, use strtobool() in the distutils.util module.

Specify multiple conditions or negations with logical operators (and, or, not)

The logical operators (and, or, not) can be used to handle logical conjunction, logical disjunction, and negation of multiple conditions.

operator(Result (in the conditional expression of an if statement)
x and ytrue if both x and y are true
x or ytrue if either x or y is true
not xfalse if x is true, true if x is false
def if_test_and_not(num):
    if num >= 0 and not num % 2 == 0:
        print('num is positive odd')
    else:
        print('num is NOT positive odd')

if_test_and_not(5)
# num is positive odd

if_test_and_not(10)
# num is NOT positive odd

if_test_and_not(-10)
# num is NOT positive odd

In fact, “x and y” and “x or y” do not return True or False, but either x or y. As long as they are used in conditional expressions in if statements, there is no need to worry about them, since they evaluate to either True or False. See the following article for details.

It is possible to use and and or more than once.

def if_test_and_not_or(num):
    if num >= 0 and not num % 2 == 0 or num == -10:
        print('num is positive odd or -10')
    else:
        print('num is NOT positive odd or -10')

if_test_and_not_or(5)
# num is positive odd or -10

if_test_and_not_or(10)
# num is NOT positive odd or -10

if_test_and_not_or(-10)
# num is positive odd or -10

Conditional expressions on new lines and multiple lines

When multiple conditional expressions are used by connecting them with “and” or “or” and each line becomes long, it is sometimes necessary to break the conditional expression and write it on multiple lines.

A line break can be made by using a backslash or by enclosing the entire line in parentheses.

def if_test_and_backslash(num):
    if num >= 0 \
       and not num % 2 == 0:
        print('num is positive odd')
    else:
        print('num is NOT positive odd')

if_test_and_backslash(5)
# num is positive odd

def if_test_and_brackets(num):
    if (num >= 0
        and not num % 2 == 0):
        print('num is positive odd')
    else:
        print('num is NOT positive odd')

if_test_and_brackets(5)
# num is positive odd

You can use a backslash to break a line as many times as you like. Likewise, you can break a line any number of times within parentheses. There is no indentation limit.

Note that this is a technique that can be used anywhere in Python code, not just in if statements.