8  Python Operators

TipLearning Objectives
  • Understand what an operator is, and why we use them
  • Recognise Python’s main groups of operators: arithmetic, comparison, logical, and assignment
  • Know that Python checks operators in a set order (precedence), and how brackets can make this clearer

8.1 What Are Operators?

An operator is a symbol or short keyword that tells Python to do something with a piece of data, such as adding two numbers together, or checking whether one value is bigger than another. Think of the mathematical symbols you already know from school, like + or < — Python uses many of the same ones.

Most operators in Python behave exactly how you would expect. You do not need to memorise every single one right now — there is a complete reference table at the end of this page for whenever you need to look one up. For now, we will focus on the four groups you will use the most: arithmetic, comparison, logical, and assignment operators.

8.2 Arithmetic Operators

Arithmetic operators do the maths you are already familiar with — adding, subtracting, multiplying, and dividing.

a = 7
b = 2

print(a + b)   # addition
print(a - b)   # subtraction
print(a * b)   # multiplication
print(a / b)   # division
9
5
14
3.5

Two of these are less familiar, and are worth a closer look:

  • % (modulus) gives you the remainder left over after dividing.
  • // (floor division) gives you the whole number result of a division, rounding down.
print(a % b)   # remainder after dividing 7 by 2
print(a // b)  # 7 divided by 2, rounded down
1
3

The + operator is not just for numbers — it also works on strings (joining them together) and on lists (combining them). We will see more of this in later sections.

8.3 Comparison Operators

Comparison operators compare two values, and always give you back a boolean — True or False.

x = 10
y = 3

print(x == y)  # equal to
print(x != y)  # not equal to
print(x > y)   # greater than
print(x < y)   # less than
False
True
True
False

8.4 Logical Operators

Logical operators combine booleans together, and are especially useful once you start writing code that makes decisions.

is_raining = True
have_umbrella = False

print(is_raining and have_umbrella)  # both must be true
print(is_raining or have_umbrella)   # either can be true
print(not is_raining)                # flips True to False, and vice versa
False
True
False

8.5 Assignment Operators

You already know the plain = operator for assigning a value to a variable. Python also has shorthand versions that update a variable using its own current value:

score = 5
score += 3  # the same as: score = score + 3
print(score)
8

8.6 A Few Other Operators

Python has several more specialised groups of operators — including bitwise operators, membership operators (in / not in), identity operators (is / is not), and operators just for sets. You will meet these properly in later sections once we have covered lists, strings, and sets in more detail, but as a quick taste, the membership operator in lets you check whether something exists inside a collection:

fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)
True

The full reference tables at the end of this page list all of these, in case you come across one sooner and want to look it up.

8.7 Order of Precedence

When an expression contains more than one operator, Python has to decide which one to work out first. It does this using a fixed order, in much the same way you were taught BODMAS or BIDMAS in school maths.

result = 2 + 3 * 4
print(result)
14

Here, Python works out 3 * 4 first, and only then adds 2, giving 14 rather than 20. If you want to force a different order, you can use brackets — just as you would in maths:

result = (2 + 3) * 4
print(result)
20

Wrapping 2 + 3 in brackets tells Python to work that part out first, giving 20 instead. When in doubt, adding brackets is always a safe way to make your intentions clear, both to Python and to anyone else reading your code.

8.8 Operator Reference Tables

You do not need to memorise these — come back to this page whenever you need to check how an operator works, or which data types it applies to.

8.8.1 Arithmetic Operators

Operator Description Example Applicable Data Types
+ Addition a + b int, float, complex, str, list, tuple, byte, bytearray
- Subtraction a - b int, float, complex
* Multiplication a * b int, float, complex, str, list, tuple, bytearray
/ Division a / b int, float, complex
% Modulus (remainder) a % b int, float
** Exponentiation a ** b int, float
// Floor Division a // b int, float

8.8.2 Comparison (Relational) Operators

Operator Description Example Applicable Data Types
== Equal to a == b int, float, str, list, tuple, set, frozenset, dict, range
!= Not equal to a != b int, float, str, list, tuple, set, frozenset, dict, range
> Greater than a > b int, float, str, range
< Less than a < b int, float, str, range
>= Greater than or equal to a >= b int, float, str, range
<= Less than or equal to a <= b int, float, str, range

8.8.3 Logical Operators

Operator Description Example Applicable Data Types
and Logical AND (both must be true) a and b bool, int
or Logical OR (either can be true) a or b bool, int
not Logical NOT (negates boolean) not a bool, int

8.8.4 Assignment Operators

Operator Description Example Applicable Data Types
= Assign a = 5 All types
+= Add and assign a += 5 int, float, str, list, tuple, bytearray
-= Subtract and assign a -= 5 int, float
*= Multiply and assign a *= 5 int, float, str, list, tuple, bytearray
/= Divide and assign a /= 5 int, float
%= Modulus and assign a %= 5 int, float
**= Exponentiate and assign a **= 5 int, float
//= Floor-divide and assign a //= 5 int, float

8.8.5 Bitwise Operators

Operator Description Example Applicable Data Types
& Bitwise AND a & b int, byte, bytearray
\| Bitwise OR a \| b int, byte, bytearray
^ Bitwise XOR a ^ b int, byte, bytearray
~ Bitwise NOT ~a int, byte, bytearray
<< Left shift a << 2 int, byte, bytearray
>> Right shift a >> 2 int, byte, bytearray

8.8.6 Membership Operators

Used to check membership within sequences (like strings, lists, tuples).

Operator Description Example Applicable Data Types
in True if value is present 'a' in 'apple' str, list, tuple, set, frozenset, dict, range
not in True if value is not present 'b' not in 'apple' str, list, tuple, set, frozenset, dict, range

8.8.7 Identity Operators

Used to compare memory locations of two objects.

Operator Description Example Applicable Data Types
is True if both refer to same object a is b All types
is not True if not same object a is not b All types

8.8.8 Unary Operators

Operate on a single operand.

Operator Description Example Applicable Data Types
- Negation (unary minus) -a int, float, complex
+ Unary plus +a int, float, complex
not Logical NOT not a bool, int

8.8.9 Set Operators

Set-specific operators.

Operator Description Example Applicable Data Types
\| Union (combine sets) a \| b set, frozenset
& Intersection (common) a & b set, frozenset
- Difference (in a not in b) a - b set, frozenset
^ Symmetric difference a ^ b set, frozenset

8.8.10 Order of Precedence

Operators are checked in a fixed order in code (think BODMAS). Using brackets can add clarity to your code, and removes any doubt about which order Python will use.

Precedence Level Operator(s) Description Example
1 (Highest) () Parentheses (brackets) for grouping expressions (a + b) * c
2 ** Exponentiation a ** b
3 +x, -x, ~x Unary plus, unary minus, bitwise NOT +a, -a, ~a
4 *, /, //, % Multiplication, division, floor division, modulus a * b, a / b
5 +, - Addition, subtraction a + b, a - b
6 <<, >> Bitwise left shift, right shift a << b, a >> b
7 & Bitwise AND a & b
8 ^ Bitwise XOR a ^ b
9 \| Bitwise OR a \| b
10 in, not in Membership operators 'a' in 'apple'
11 <, >, <=, >=, ==, != Comparison operators a < b, a == b
12 is, is not Identity operators a is b
13 not Logical NOT not a
14 and Logical AND a and b
15 or Logical OR a or b
16 (Lowest) =, +=, -=, *=, /=, //=, %=, **=, &=, ^=, \|=, <<=, >>= Assignment operators a = 5, a += 5

8.9 Exercises

ExerciseExercise 1 - Guess the Output: Arithmetic

Before running any code, write down what you think each of these will print:

print(7 + 2)
print(7 % 2)
print(7 // 2)
print(2 ** 3)

Once you have made your guesses, run them for real. Were you right?

print(7 + 2)
print(7 % 2)
print(7 // 2)
print(2 ** 3)
9
1
3
8
  • 7 + 2 is simple addition, giving 9.
  • 7 % 2 gives the remainder after dividing 7 by 2, which is 1.
  • 7 // 2 gives the whole number result of dividing 7 by 2, rounded down, which is 3.
  • 2 ** 3 means 2 to the power of 3 (2 × 2 × 2), giving 8.
ExerciseExercise 2 - Guess the Output: Comparisons and Logic

Before running any code, write down True or False for each line:

print(5 > 3)
print(5 == "5")
print(5 > 3 and 2 > 1)
print(5 > 3 and 2 > 10)
print(5 > 3)
print(5 == "5")
print(5 > 3 and 2 > 1)
print(5 > 3 and 2 > 10)
True
False
True
False
  • 5 > 3 is True, since 5 is bigger than 3.
  • 5 == "5" is False — even though they look similar, an integer (5) and a string ("5") are never treated as equal in Python.
  • 5 > 3 and 2 > 1 is True, because both parts are true.
  • 5 > 3 and 2 > 10 is False, because the second part is false, and and needs both sides to be true.
ExerciseExercise 3 - Using Operators in a Script

Level:

Open the Python console and try out a few operators from the tables below on your own numbers.

There is no single correct answer here the aim is to recap how to use the console while testing different operators. The console is a great place for testing these where you do not want to save the output.

8.10 Summary

Use the tables above to look up any operator you come across in Python. Operators can make code more concise and readable, and are usually intuitive even to those new to Python. On the other hand, operators can sometimes make code harder to read than using a named function instead, and cannot generally be passed as arguments into higher-order functions. We will look at functions in more detail in the next section.

Operators also behave differently depending on the data type they are used with — try using the * operator to multiply two integers, and then to multiply a string by an integer, to see what happens. We will use operators much more in the next few sections.

TipKey Points
  • Python has a rich set of operators, grouped by the kind of operation they perform
  • Operators can behave differently when used with different data types and structures
  • Operators are checked in a fixed order of precedence in code, in the same way as in mathematics