I1 · Python Programming for AI

Operators and Expressions

An operator is a symbol that performs an operation on values. An expression combines values, variables and operators into something Python can evaluate to a single value. Python has arithmetic, assignment, comparison and logical operators, evaluated in a fixed order of precedence.

10 min Intermediate Jump to the activity

What you need: The earlier topics of this module.

Definition

What is 2 + 3 × 4 to Python: 20 or 14?

An operator is a symbol that performs an operation on values. An expression combines values, variables and operators into something Python can evaluate to a single value. Python has arithmetic, assignment, comparison and logical operators, evaluated in a fixed order of precedence.

In simple words

Python follows the same order as school maths: brackets first, then powers, then multiply and divide, then add and subtract. So 2 + 3 * 4 is 14. Comparisons such as 5 > 3 give True or False, and 'and', 'or' and 'not' combine those answers.

Why it matters

Every calculation in a program, from a shopping bill to a model's error, is an expression. Getting the order right avoids silent bugs where the program runs but gives the wrong number.

How it works

OperatorMeaningExampleResult
+ - *Add, subtract, multiply6 * 742
/Divide (always a float)7 / 23.5
//Whole-number division7 // 23
%Remainder7 % 21
**Power2 ** 38
== != < >Compare5 > 3True
and or notCombine True/FalseTrue and FalseFalse

In code

A bill with quantity, discount and a free-delivery check.

shopping_bill.py
price = 120
quantity = 3
discount_percent = 10

subtotal = price * quantity
discount = subtotal * discount_percent / 100
total = subtotal - discount
print("Subtotal:", subtotal)
print("Discount:", discount)
print("Total:", total)

free_delivery = total >= 300 and quantity >= 2
print("Free delivery?", free_delivery)

print("2 + 3 * 4 =", 2 + 3 * 4)
print("(2 + 3) * 4 =", (2 + 3) * 4)
print("17 // 5 =", 17 // 5, "and 17 % 5 =", 17 % 5)

Output

Subtotal: 360
Discount: 36.0
Total: 324.0
Free delivery? True
2 + 3 * 4 = 14
(2 + 3) * 4 = 20
17 // 5 = 3 and 17 % 5 = 2

Try it yourself

Predict the result

Work out each expression in Python's order, then match it to its value.

  • 2 + 3 * 4
  • (2 + 3) * 4
  • 10 // 3
  • 10 % 3
  • 2 ** 4
  • 5 > 3 and 2 > 4

Common mistakes

  • Using = when you mean ==.
  • Forgetting that * happens before +. Use brackets when in doubt.
  • Confusing / and //: 7 / 2 is 3.5 but 7 // 2 is 3.

Check yourself

Question 1

1. What is 10 - 2 * 3?

Question 2

2. What does 9 % 4 give?

Question 3

3. Which compares two values?

Summary

  • Expressions combine values with operators into one value.
  • Precedence: brackets, powers, * / // %, then + -.
  • Comparisons give True or False; and, or, not combine them.

Finished reading?

Sources: Python docs: Operator precedence