Sub topic 1
Expressions, operands and operators
Prerequisites
This chapter assumes you can do the following:
- Run a script or use the REPL (the interactive prompt started by
python). - Recognize the core built-in types:
int,float,str,bool,listanddict. - Create variables with simple assignment, such as
x = 5.
You do not need to know any operator in detail yet. Later chapters cover each family one by one. This chapter gives you the vocabulary and the evaluation model they all share.
What an expression is
An expression is a piece of code that Python can evaluate to produce a value. Every expression has a value and a type.
print(3 + 4)
x = 10
print(x * 2 + 1)
print(-x)
print(not x)
print(type(3 + 4.0))This prints 7, 21, -10, False and <class 'float'>. Each of 3 + 4, x * 2 + 1, -x, not x and type(3 + 4.0) is an expression. Simpler expressions exist too: a literal such as 42, a name such as x, or a call such as len("abc"). Larger expressions are built by combining smaller ones.
A statement is different. A statement performs an action and does not produce a value you can use. Examples are x = 5, if, for and import. Some statements contain expressions, and any expression can stand alone as a statement. A call like print(x) is an expression used as a statement, and Python discards its value.
Here is a quick test. If you can put the code inside print(...) or on the right side of =, it is an expression.
Operands and operators
An operator is a symbol or keyword that tells Python to compute something. An operand is a value the operator works on. In 3 + 4, the + is the operator and 3 and 4 are its operands. An operand can itself be any expression, so expressions nest to any depth.
Operators are grouped by arity, which is the number of operands they take:
| Arity | Meaning | Example |
|---|---|---|
| Unary | One operand | `-x`, `not flag`, `~n` |
| Binary | Two operands | `a + b`, `a and b`, `a in items` |
| Ternary | Three operands | `a if cond else b` |
Some symbols are unary and binary at once. In -x the minus sign negates, and in a - b it subtracts. Python decides which meaning applies from the position of the symbol.
Operators also come in keyword form. and, or, not, in, is and if ... else are all operators even though they look like words.
The families of operators
Python has several operator families. The rest of this tutorial covers each in its own chapter.
| Family | Examples | Column |
|---|---|---|
| Arithmetic | `+`, `-`, `*`, `/`, `//`, `%`, `**` | |
| Comparison | `==`, `!=`, `<`, `<=`, `>`, `>=` | |
| Identity | `is`, `is not` | |
| Membership | `in`, `not in` | |
| Logical | `and`, `or`, `not` | |
| Bitwise | `&`, `\ | `, `^`, `~`, `<<`, `>>` |
| Assignment forms | `+=`, `-=`, `:=` | |
| Conditional | `x if cond else y` |
One point often confuses people. Plain = is not an operator. It belongs to the assignment statement, so y = (x = 3) is a syntax error. The walrus operator := is the assignment form that is an expression.
How Python evaluates an expression
Python turns an expression into a tree. Each operator becomes a node, and its operands become the children. Python evaluates the leaves first and works upward, so every operator receives finished values.
The tree shows the grouping. Because * sits lower in the tree, 3 * 4 is computed first (giving 12), and then 2 + 12 gives 14. Precedence and associativity are the rules that decide this shape, and a later chapter covers them fully. Parentheses override them, so (2 + 3) * 4 produces a different tree.
Grouping is not the same as order of evaluation
Precedence decides which operands belong to which operator. It does not change the order in which Python evaluates the operands themselves. Operands are evaluated from left to right.
def show(label, value):
print("evaluating", label)
return value
result = show("a", 1) + show("b", 2) * show("c", 3)
print(result)The output is:
evaluating a
evaluating b
evaluating c
7The multiplication binds tighter, but a is still evaluated first. The calls run in the order they appear in the text. This matters when operands have side effects, meaning they change something besides returning a value, such as printing, mutating a list or reading input.
Some operators skip operands. and, or and the conditional expression evaluate only the operands they need. That behavior is called short-circuiting, and a later chapter covers it.
Operators call methods
An operator is not magic. For most operators, Python calls a special method on the left operand, with the right operand as the argument. For integers, 3 + 4 does roughly what this code does:
print(3 + 4)
print((3).__add__(4))Both lines print 7. This design is why + adds numbers, joins strings and concatenates lists. Each type defines what the operator means for it. A class you write can define the same methods, and the final chapter of this tutorial shows how.
If the types do not support the operator together, Python raises a TypeError instead of guessing:
try:
print("age: " + 30)
except TypeError as error:
print(error)The message reads can only concatenate str (not "int") to str. The usual fix is to convert one operand explicitly, for example "age: " + str(30), or to use an f-string.
Common errors
- Reading
=as an operator. Assignment is a statement. Use:=only when you need to bind a name inside a larger expression. - Assuming precedence controls evaluation order. It controls grouping. Operands still run left to right.
- Using a method's result as a value. Methods like
list.appendandlist.sortmutate the list and returnNone. The expressionitems = items.append(4)setsitemstoNone. - Mixing types in one operator.
"3" + 4fails, while"3" * 4works and gives"3333", because*accepts a string and an integer. Check the operand types when you see aTypeError. - Leaving out parentheses in long expressions. Parentheses cost nothing at runtime. They make the grouping obvious to the next reader, even when the default precedence would give the same result.
Reading an expression step by step
Take the following code:
price = 20
quantity = 3
discount = 5
total = price * quantity - discount if quantity > 2 else price * quantity
print(total)Work through it from the outside in. The outermost operator is the conditional ... if quantity > 2 else .... Python first evaluates the condition quantity > 2, which is True. Then it evaluates only the first branch, price * quantity - discount. There, * runs before -, giving 60 - 5, which is 55. The else branch is never evaluated. The printed value is 55.
This habit of finding the outermost operator, then its operands, then recursing, lets you predict any expression in the chapters ahead.
Exercise
In the code print(show("x", 2) + show("y", 3) * show("z", 4)), where show prints its label and returns its value, in what order are the labels printed, and what value is printed last?
Show answer
The labels print in the order x, y, z, because operands are evaluated left to right even though * has higher precedence than +. The last value printed is 14, since 3 * 4 is 12 and 2 + 12 is 14.
Exercise
Is each of these an expression, a statement, or both: x = 5, x + 5, print(x)?
Show answer
x = 5 is an assignment statement and not an expression. x + 5 is an expression and can also be used alone as a statement. print(x) is a call expression whose value is None, usually used alone as a statement.