Operators in Python: computing, comparing, combining

An operator turns one or two values into a result: addition, comparison, assignment. Python's five families, their priority and their traps.
5 min read
Believemy logo

Definition

Writing a program means constantly solving small problems: adding two numbers, checking a threshold, deciding whether two conditions hold at once. An operator answers that need: it takes one or two values, acts on them, and hands back a result. + adds, > compares, = stores.

These symbols are the most elementary bricks of the language: any expression comes down to a series of operators applied to values. Here are three families gathered in a single example.

PYTHON
total = 12 + 8                 # arithmetic
enough = total >= 20           # comparison
valid = enough and total < 100 # logical

The values it works on are called operands. One detail often surprises early on: an operator almost never changes them, it builds a brand new value instead, which vanishes the instant it is computed if it is not stored anywhere, for instance in a variable.


The five families

Python holds around forty operators, too many to memorise one by one. What matters is not how they are written, but what they hand back once the action is done: five families cover everything.

FamilyWritingResult produced
Arithmetic+ - * / // % **A number
Comparison== != < > <= >=A bool
Logicaland, or, notA boolean, or one of the operands
Membership and identityin, isTrue or false
Assignment= += -= *= //=Nothing, they store a value

Remembering an operator by its result rules out the most frequent confusion of early learning: believing every symbol combines freely. A comparison hands back a boolean, so it belongs inside a condition; an assignment hands back nothing, and Python refuses to place it there.


Priority changes the result

As long as an expression holds a single operator, there is nothing to settle. The trouble starts once several are mixed: Python has to decide in what order to apply them, and that order can change the outcome. The rule resembles the one learned in mathematics: exponentiation before multiplication, multiplication before addition, comparison before the logical operators, and among those, not before and, itself before or.

Two examples show it, the second far more consequential than the first.

PYTHON
2 + 3 * 4
# 14, not 20

age > 18 and country == "FR" or admin
# read as: (age > 18 and country == "FR") or admin
Warning

That second line is a production bug waiting to happen: an administrator account walks through the door whatever their age, because the final or scoops up everything before it. Brackets cost nothing and always beat remembering the priority table, even when they are technically redundant.


Four traps worth knowing

The first hangs on a single sign. = stores a value, == compares two values. Mixing them up does not produce a wrong answer: Python simply refuses to run the line and raises a syntax error, catchable before the program even runs. Assigning mid-expression remains possible, under the distinct writing of the walrus operator.

The second concerns division: do two integers that divide evenly hand back a whole number? No, / always hands back a float: 10 / 2 is 5.0, not 5. A whole number takes //, which truncates the decimal part. Dividing by zero gives no infinity at all: Python raises a ZeroDivisionError, which stops the program if nothing catches it.

The third comes from +, which shifts meaning with whatever it is given: it adds, joins two strings end to end, merges two lists. Mixing the kinds, a number and a string for instance, raises a TypeError, the commonest failure on user input, which always arrives as text.

The fourth sets == against is, the hardest to spot, because the two often answer alike without actually being alike. The first asks whether two values are equal, the second whether they are the same object in memory. Python sometimes reuses the same object on small numbers; on lists or larger numbers, they diverge. In practice, is has one real use, comparing a value to None.


Frequently asked questions

Question

What is the percent operator for?

The % symbol gives the remainder of an integer division: 17 % 5 is 2, since 5 goes into 17 three times with two left over. Its commonest use remains the divisibility test, with number % 2 == 0 to recognise an even number, or i % 10 == 0 to fire an action once every ten turns of a loop.

Question

Can two comparisons be chained?

Yes, and it is a Python speciality: 0 < score <= 20 is written in one piece and reads like mathematics. Most languages force two separate comparisons joined by an and here, a longer and less readable form.

Question

Why do and and or not always hand back true or false?

Because they hand back the operand that settled the matter rather than a boolean: "" or "default" is the string "default", not True. They also stop as soon as the result is known, which allows checking that a value exists before the access that would fail on it. These shortcuts save lines once they become second nature, and our Python course puts them to work throughout its exercises.

Related terms

Discover our python glossary

Browse the terms and definitions most commonly used in development with Python.

Share this article

Want to help us? Share this article on your networks or even better: on your site, in an article or in your newsletter.