ZetCode

Python and keyword

last modified November 29, 2026 Python 3.15

In this article we show how to use the and keyword in Python.

The and keyword is a logical operator. The expression x and y is true only when both x and y are true. It is used mainly to combine conditions in if and while statements. Python's and works with any values, not only with True and False, and it evaluates its right operand only when it is needed.

The other logical operators are or and not. All operators are summarised in Python operators; this article looks at and in detail.

The truth table

With boolean operands, and gives True only if both operands are True.

truth_table.py
for a in [True, False]:
    for b in [True, False]:
        print(a, "and", b, "->", a and b)

Two nested loops go through all four combinations of the operands. Three of them give False.

$ python truth_table.py
True and True -> True
True and False -> False
False and True -> False
False and False -> False

Combining conditions

The most common use of and is joining several conditions that all have to hold.

conditions.py
age = 34
income = 2800
has_debt = False

if age >= 18 and income > 2000 and not has_debt:
    print("loan approved")
else:
    print("loan refused")

temperature = 23
humidity = 85

if temperature > 20 and humidity > 80:
    print("hot and humid")

user = "admin"
password = "s3cret"
print(user == "admin" and password == "s3cret")

The loan is approved only when the age, the income, and the absence of debt are all acceptable. More than two conditions can be chained; each additional and adds one more requirement. A comparison joined with and is an ordinary expression, so it can also be printed or assigned to a variable.

$ python conditions.py
loan approved
hot and humid
True

The returned value

The and operator does not always return a boolean. If the left operand is false, it returns the left operand; otherwise it returns the right operand. Values such as 0, an empty string, an empty list, and None count as false; most other values count as true.

operands.py
print(3 and 5)
print(0 and 5)
print(repr("" and "text"))
print(repr("text" and ""))
print([1, 2] and [3])
print(None and 7)

print(bool(3 and 5))
print(type(3 and 5))

3 and 5 returns 5: the left operand is true, so the result is the right operand. 0 and 5 returns 0, the first false operand. In an if statement this makes no difference, because the returned value is tested for truth. The bool function converts the result to True or False when a real boolean is needed. The rules of truth testing are described in Python data types.

$ python operands.py
5
0
''
''
[3]
None
True
<class 'int'>

Short-circuit evaluation

When the left operand of and is false, the result is already known, and the right operand is not evaluated at all. This is called short-circuit evaluation. It allows the left condition to guard the right one.

short_circuit.py
count = 0
total = 120

if count != 0 and total / count > 10:
    print("high average")
else:
    print("no average")

items = []
if items and items[0] == "start":
    print("starts with start")
print("items checked")

config = {"debug": True}
if "level" in config and config["level"] > 2:
    print("verbose")
print("config checked")

Because count != 0 is false, the division by zero is never attempted. An empty list is false, so items[0] is not evaluated and no IndexError occurs. In the same way, config["level"] is looked up only after the membership test confirms that the key exists. The order of the operands matters: with the conditions swapped, each of these tests would raise an exception.

$ python short_circuit.py
no average
items checked
config checked

Order of evaluation

A chain of and operators is evaluated from left to right and stops at the first false operand. A function that prints its name shows which operands are evaluated.

evaluation_order.py
def check(name, result):
    print("checking", name)
    return result


if check("disk", True) and check("memory", False) and check("network", True):
    print("all systems ready")
else:
    print("system not ready")

print("---")

if check("disk", False) and check("memory", True):
    print("ready")

In the first chain, the memory check fails, so the network check is never called. In the second chain, the disk check fails, and the memory check is skipped. When the operands are function calls with side effects or with a cost, cheap and likely-to-fail checks should come first.

$ python evaluation_order.py
checking disk
checking memory
system not ready
---
checking disk

Chained comparisons

A range test such as 0 <= x and x <= 100 can be written as a chained comparison, 0 <= x <= 100. Python evaluates a chain of comparisons as comparisons joined with and.

chained.py
x = 42

print(0 <= x and x <= 100)
print(0 <= x <= 100)

a, b, c = 1, 5, 3
print(a < b < c)
print(a < b and b < c)

grade = 87
if 80 <= grade < 90:
    print("grade B")

low, high = 10, 20
print(low < 15 < high != 0)

The chained form is shorter and evaluates the middle operand only once. a < b < c means a < b and b < c; it says nothing about a and c. Like and, the chain stops at the first false comparison. Any comparison operators can be chained, including !=.

$ python chained.py
True
True
False
False
grade B
True

Precedence with or and not

The logical operators have different priorities: not binds most tightly, then and, then or. An expression that mixes and with or is grouped around the and first.

precedence.py
print(True or True and False)
print((True or True) and False)

is_admin = True
is_owner = False
locked = True

print(is_admin or is_owner and not locked)
print((is_admin or is_owner) and not locked)

print(not False and False)
print(not (False and False))

True or True and False is read as True or (True and False) and gives True. In the access rule, the unparenthesised form grants access to an administrator even when the resource is locked; the version with parentheses requires the resource to be unlocked for everyone. not False and False applies not to the first operand only. Parentheses make the intended grouping explicit and are recommended whenever and and or are mixed.

$ python precedence.py
True
False
True
False
False
True

and versus the & operator

The & operator is the bitwise AND. On integers it combines the bits of the operands; on booleans it gives the same result as and, but it always evaluates both operands. It also has a higher priority than comparisons, which makes it a source of errors.

bitwise.py
a, b = 6, 3

print(a and b)
print(a & b)

print(True & False, True and False)

x, y = 5, 3
print(x > 0 and y > 0)
print(x > 0 & y > 0)
print((x > 0) & (y > 0))

6 and 3 returns 3, the second operand, while 6 & 3 computes the bits 110 & 011, which is 2. The expression x > 0 & y > 0 is parsed as x > (0 & y) > 0, a chained comparison that is false, although both numbers are positive. With parentheses around the comparisons the result is correct. For conditions, use and. The & operator is used with integers, sets, and libraries such as NumPy and pandas, which define it for element-wise operations.

$ python bitwise.py
3
2
False False
True
False
True

Default values with and

Because and returns one of its operands, it can apply an operation only when a value is present. If the value is empty or None, the expression returns it unchanged.

defaults.py
name = "  Lucia  "
clean = name and name.strip()
print(repr(clean))

name = ""
clean = name and name.strip()
print(repr(clean))

name = None
clean = name and name.strip()
print(repr(clean))

data = [4, 8, 15]
first = data and data[0]
print(first)

data = []
first = data and data[0] or "empty"
print(first)

name and name.strip() calls strip only for a non-empty string; for an empty string or None, the value is returned as it is and no AttributeError occurs. data and data[0] gives the first element of a non-empty list. Combined with or, the expression supplies a fallback, but this idiom fails when the wanted value is itself false, for example 0. A conditional expression, data[0] if data else "empty", is often clearer.

$ python defaults.py
'Lucia'
''
None
4
empty

Many conditions with all

When the conditions are stored in a list, the built-in all function tests them together. It returns True when every item is true, which is the same as joining the items with and.

all_conditions.py
password = "Tr0ub4dor&3"

long_enough = len(password) >= 8
has_upper = password != password.lower()
has_lower = password != password.upper()
has_symbol = not password.isalnum()

print(long_enough and has_upper and has_lower and has_symbol)

checks = [long_enough, has_upper, has_lower, has_symbol]
print(checks)
print(all(checks))

print(all([]))
print(all([1, "a", [0]]))
print(all([1, "", [0]]))

The password rules are stored in four variables and combined twice, once with and and once with all. For an empty list, all returns True, because no item is false. The items are tested for truth, so [0], a non-empty list, counts as true, while the empty string makes the last call false. Like and, all stops at the first false item. The function is covered in Python any and all.

$ python all_conditions.py
True
[True, True, True, True]
True
True
True
False

Source

Boolean operations, Comparisons, Operator precedence, Truth value testing

In this article we have combined conditions with the and keyword, seen that it returns one of its operands, used short-circuit evaluation to guard expressions, written chained comparisons, looked at precedence with or and not, compared and with the bitwise & operator, and tested many conditions with all. See also Python operators, Python control flow, and Python None keyword.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.