Python Tutorial › Basics › Operators & Booleans

Python Operators & Booleans

BeginnerLesson 12 of 4712 min read12 runnable examples

Operators are the symbols that do the work in an expression: they add numbers, compare values and combine conditions. This lesson covers all seven groups of Python operators and the booleans they produce.

Advertisement
In this lesson
  • Arithmetic and assignment operators
  • Comparison operators and chaining
  • and, or, not with short-circuiting
  • is vs == and the in operator

Arithmetic operators

Python
a, b = 14, 4print(a + b, a - b, a * b)print(a / b, a // b, a % b, a ** 2)
Output
18 10 56
3.5 3 2 196

+ and * also work on strings and lists:

Python
print("ab" + "cd", "-" * 10)print([1, 2] + [3], [0] * 3)
Output
abcd ----------
[1, 2, 3] [0, 0, 0]

The Numbers & Math lesson explains //, % and rounding in detail.

Assignment operators

Augmented assignment updates a variable using its current value.

OperatorSame as
x += 3x = x + 3
x -= 3x = x - 3
x *= 3x = x * 3
x /= 3x = x / 3
x //= 3x = x // 3
x %= 3x = x % 3
x **= 3x = x ** 3
Python
balance = 1000balance -= 250      # withdrawalbalance *= 1.05     # 5% interestprint(balance)
Output
787.5

Comparison operators

Comparisons return a boolean: True or False.

OperatorMeaning
==equal
!=not equal
> / <greater than / less than
>= / <=greater or equal / less or equal
Python
score = 72print(score == 72, score != 72)print(score > 50, score <= 60)print("apple" < "banana")     # strings compare alphabeticallyprint(10 == 10.0)             # int and float with the same value are equal
Output
True False
True False
True
True

Python lets you chain comparisons, just like in maths:

Python
age = 25print(18 <= age < 60)
Output
True

Logical operators: and, or, not

ExpressionTrue when
a and bboth are true
a or bat least one is true
not aa is false
Python
has_ticket = Trueis_adult = Falseprint(has_ticket and is_adult)print(has_ticket or is_adult)print(not is_adult)
Output
False
True
True

Short-circuiting

and stops at the first falsy value and or stops at the first truthy value. They return that value itself, not always True/False. This gives two handy idioms:

Python
name = ""display = name or "Guest"          # default when name is emptyprint(display) items = []print(len(items) > 0 and items[0])  # items[0] is never evaluated
Output
Guest
False

Booleans and truthiness

True and False are the two boolean values, and bool is a subclass of int. In an if or while, any value is treated as true or false:

Python
print(True + True, True * 10)for value in [0, 3, "", "text", [], [1], None]:    print(repr(value), "->", "truthy" if value else "falsy")
Output
2 10
0 -> falsy
3 -> truthy
'' -> falsy
'text' -> truthy
[] -> falsy
[1] -> truthy
None -> falsy

Identity operators: is, is not

== asks “do these have the same value?” is asks “are these the very same object?”

Python
a = [1, 2]b = [1, 2]c = aprint(a == b, a is b)print(a is c)
Output
True False
True
Tip

Use is only to compare with None, True or False: if result is None:. For everything else use ==.

Membership operators: in, not in

Python
roles = ["admin", "tester", "viewer"]print("tester" in roles)print("guest" not in roles)print("py" in "python")                  # substring checkprint("id" in {"id": 7, "name": "x"})   # checks dict keys
Output
True
True
True
True

Bitwise operators

Bitwise operators work on the binary digits of integers. You will meet them in permissions, flags and low-level code.

Python
a, b = 6, 3       # 110 and 011 in binaryprint(a & b, a | b, a ^ b)print(~a, a << 1, a >> 1)
Output
2 7 5
-7 12 3

Operator precedence

From highest to lowest (operators on the same row are evaluated left to right, except **):

PrecedenceOperators
1() parentheses
2**
3+x, -x, ~x
4*, /, //, %
5+, -
6bitwise: << and >>, then &, then ^, then bitwise OR
7comparisons, in, not in, is, is not
8not
9and
10or
Python
print(True or False and False)    # and binds tighter: True or (False and False)print(not 1 == 2)                 # not (1 == 2)
Output
True
True

Check your understanding

Predict the output

x = 5print(x > 3 and x < 10, x > 3 or 1 / 0, 0 or "" or "last")

Quick quiz

1. What does 10 != 10.0 return?

2. What does "" or "default" return?

3. Which checks whether x is None?

4. What does 1 < 3 < 2 evaluate to?

Exercise: leap year check

A year is a leap year if it is divisible by 4, except years divisible by 100, unless they are also divisible by 400. Print each year with True or False.

Input
1900, 2000, 2024, 2026
Expected output
1900 False
2000 True
2024 True
2026 False
Hint 1

Combine % with and and or.

Hint 2

(year % 4 == 0 and year % 100 != 0) or year % 400 == 0

Program Practice

Python operators FAQ

What is the difference between == and is in Python?

== compares values; is compares identity (whether two names refer to the same object). Two separate lists with the same items are == but not is.

Does Python have && and || operators?

No. Python uses the words and, or and not.

Does Python have ++ and — operators?

No. Use x += 1 and x -= 1.

What does the % operator do in Python?

It returns the remainder of a division (17 % 5 is 2). It is also used in old-style string formatting such as "%d items" % 3.

Leave a Comment