Skip to content

Python short circuit

  • by

Python short circuit means stoppage of execution of a boolean operation if the truth value of expression has been determined already. Python both and and or operators short-circuit.

These are the short-circuiting case Boolean operations, ordered by ascending priority:

OperationResultNotes
x or yif x is true, then x, else yThis is a short-circuit operator, so it only evaluates the second argument if the first one is false.
x and yif x is false, then x, else yThis is a short-circuit operator, so it only evaluates the second argument if the first one is true.
not xif x is false, then True, else Falsenot has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.

Python short circuit example

Simple example code.

# Short Circuit Logical AND
False and print('Hello False')
True and print('Hello True')

# Short Circuit Logical OR
a = 1 > 0
if a or (1 / 0 == 0):
print('ok')
else:
print('nok')

Output:

Python short circuit

Short-Circuiting in all() and any()

# helper function
def check(i):
    print("SC")
    return i


print(all(check(i) for i in [1, 0, 1, 0, 3]))

print(any(check(i) for i in [0, 0, 1, 1, 3]))

Do comment if you have any doubts or suggestions on this Python topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading