Beginner   Chapter 24 · 25 min read · Module 2: Operators and Expressions

Logical Operators

Learning objectives
  • After this chapter you can use and, or and not to combine conditions.
  • You can predict the result of a logical expression using a truth table and operator priority.
  • You can explain short-circuit evaluation and use it to avoid errors.
  • You can say which values are truthy or falsy and what and/or really return.
  • You can write clear if statements that mix comparisons and logical operators.

Real programs rarely make a choice from one simple fact. A shop may give a discount only if the customer is a member and the bill is above a limit. A game may end if the player has no lives or the time is over. To write rules like these you need a way to join small conditions into bigger ones. That is the job of logical operators.

Python keeps this part of the language friendly. Instead of symbols such as && or ||, which you may have seen in other languages, Python uses the words and, or and not. The code reads almost like English, so it is easier for beginners and for people who read your program later.

In this chapter you will learn what each operator does, how Python decides the order of evaluation, and what short-circuiting means. You will also see a feature that surprises many learners: and and or can return values other than True and False. Once you know it, you can use it safely.

What logical operators do

Logical operators combine or reverse conditions. A condition is any expression that Python can treat as true or false, such as age >= 18 or name == "Asha". Python has exactly three logical operators: and, or and not. They are written as plain English words, which makes code easy to read aloud: "if the user is logged in and has paid".

Logical operator: an operator that joins or reverses true/false conditions and is used mostly inside if and while statements

The and operator

a and b is true only when both sides are true. If either side is false, the whole expression is false. Use it when several rules must all be satisfied, for example a person must be old enough and must also have a ticket.

Example 1: and, or and not with booleans
age = 20
has_ticket = True
print(age >= 18 and has_ticket)
print(age >= 18 and not has_ticket)
print(age < 18 or has_ticket)
print(not has_ticket)
True False True False

The or operator

a or b is true when at least one side is true. It is false only when both sides are false. Use it when any one of several choices is good enough, for example a day is a weekend if it is Saturday or Sunday.

The not operator

not a flips the value: true becomes false and false becomes true. It works on one value only, so it is called a unary operator. not has a higher priority than and, and and has a higher priority than or. When you are unsure, use brackets to make your meaning clear.

ExpressionResultRule
True and TrueTrueboth must be true
True and FalseFalseone false makes it false
False or TrueTrueone true is enough
False or FalseFalseboth false
not TrueFalseflips the value

Short-circuit evaluation

Python reads logical expressions from left to right and stops as soon as the answer is known. In a and b, if a is false, Python does not look at b, because the result cannot become true. In a or b, if a is true, Python skips b. This is called short-circuiting. It is not only a speed trick. It lets you write safe checks, such as testing that a divisor is not zero before you divide.

Example 2: short-circuit protects from an error
def check(label, value):
    print("checking", label)
    return value

print(check("A", False) and check("B", True))
print(check("C", True) or check("D", False))

n = 0
print(n != 0 and 10 / n > 1)
checking A False checking C True False

and and or return one of their operands

This surprises many beginners. Logical operators in Python do not always return True or False. They return one of the two values you gave them. x or y gives x if x is truthy, otherwise y. x and y gives x if x is falsy, otherwise y. Values such as 0, 0.0, an empty string, an empty list, an empty dictionary and None are falsy. Almost everything else is truthy. Only not always returns a real boolean.

Example 3: truthy and falsy results
name = ""
print(name or "Guest")
print("Mia" or "Guest")
print(0 and 5)
print(3 and 5)
print([] or "empty list")
print(not [], not [1])
Guest Mia 0 5 empty list True False

The pattern value or default is common for filling in a missing value. Be careful, though: 0 and an empty string are also falsy, so count or 10 replaces a real zero with 10. If zero is a valid value, test with is None instead.

Chaining conditions in real code

Logical operators are most useful in if statements. You can mix all three, and you can combine them with comparison operators. Python also lets you chain comparisons like 0 <= x < 10, which means the same as 0 <= x and x < 10 and is easier to read.

Example 4: a small login rule
username = input()
age = int(input())
if username != "" and (age >= 13 or username == "parent"):
    print("welcome", username)
else:
    print("access denied")
welcome mia
Tip: write each condition on its own, give long conditions a name such as is_adult = age >= 18, and then combine the names. Your code becomes much easier to read and test.

Python syntax

Syntax
condition1 and condition2
Syntax
condition1 or condition2
Syntax
not condition
Syntax
result = value or default_value

Real-world applications

  • Checking several rules at once in form validation, such as a password that is long enough and contains a digit.
  • Controlling loops with several stop reasons, for example stopping when the list is empty or a limit is reached.
  • Choosing a default value when a setting is missing or empty.
  • Guarding risky operations, such as checking that a list is not empty before reading its first item.
  • Filtering data, for example selecting rows where the city is Pune or the city is Delhi.

Common mistakes

Mistake: Writing if x == 1 or 2: and expecting it to test both numbers.
Fix: 2 alone is always truthy, so the condition is always true. Write x == 1 or x == 2 or x in (1, 2).
Mistake: Forgetting that and binds tighter than or, so a or b and c is read as a or (b and c).
Fix: Add brackets to show what you mean, for example (a or b) and c.
Mistake: Assuming x or y always gives True or False.
Fix: Remember that it returns one of the operands. Wrap it in bool(...) if you need a real boolean.
Mistake: Using value or default when 0 or an empty string is a valid value.
Fix: Use value if value is not None else default instead.
Mistake: Using the bitwise symbols & and | for ordinary conditions.
Fix: Use and and or. The symbols work on bits and do not short-circuit.

Important tips

  • Use brackets in long conditions even when they are not required.
  • Put the cheap or most likely test first so short-circuiting saves work.
  • Name complex conditions with variables such as is_valid.
  • Use not with in and is in the readable forms not in and is not.

Key points summary

  • Python has three logical operators: and, or, not.
  • and needs both sides true; or needs at least one true; not flips a value.
  • Priority from high to low is not, and, or.
  • Evaluation stops early (short-circuit) when the answer is known.
  • and and or return one of the operands, not always a boolean.
  • Falsy values include 0, 0.0, empty string, empty containers and None.

Exam and interview points

  • Priority order: not, then and, then or.
  • x or y returns x if x is truthy, else y; x and y returns x if x is falsy, else y.
  • Short-circuiting means the right operand may not be evaluated.
  • not always returns a bool; and and or may not.
  • x == 1 or 2 is a classic bug because 2 is always truthy.

Quick revision

  • and: both true. or: at least one true. not: flip.
  • not > and > or in priority.
  • Short-circuit: stop once the answer is known.
  • and/or return an operand; not returns a bool.
  • Falsy: 0, empty things, None, False.

Frequently asked questions

What is the difference between and and &?

`and` is a logical operator that works on truth values and short-circuits. `&` is a bitwise operator that works on the bits of integers (and on sets) and always evaluates both sides.

Why does `print(0 or 5)` show 5 and not True?

`or` returns the first truthy operand it finds. Since 0 is falsy, it returns the second operand, 5.

Can I use not with other operators?

Yes. `not a == b` means `not (a == b)` because comparison has higher priority than not. Still, `a != b` is easier to read.

Is there an xor operator?

There is no logical xor word. For booleans you can write `a != b`, or use the bitwise `^` operator.

Does Python evaluate both sides of and and or?

Not always. It stops as soon as the result is known, so the right side may never run.

Practise this chapter

19 practice questions Take the chapter quiz

Related chapters