Skip to content
Topic 3 of 6

Operators & Expressions

Do maths, compare values, combine conditions and build strings with Python's operators.

18 min read 4 pages 5 practice games Jump to practice ↓

Page 1

Arithmetic operators

The basic arithmetic operators are:

  • Addition (+): 7 + 2 is 9.
  • Subtraction (-): 7 - 2 is 5.
  • Multiplication (*): 7 * 2 is 14.
  • True division (/): 7 / 2 is 3.5. Division with / always returns a float, even 6 / 2 gives 3.0.
  • Floor division (//): 7 // 2 is 3. Floor division rounds down to the nearest whole number, so -7 // 2 is -4.
  • Modulo (%): 7 % 2 is 1. The modulo operator gives the remainder of a division, so n % 2 == 0 tests whether n is even.
  • Exponentiation (**): 2 ** 3 is 8.

If either operand is a float, the result is a float: 3 + 1.0 is 4.0. Dividing by zero with /, // or % raises a ZeroDivisionError.

python
minutes = 135
print(minutes // 60)   # 2  (hours)
print(minutes % 60)    # 15 (minutes left over)
print(2 ** 10)         # 1024

Page 2

Comparison and logical operators

Comparison operators compare two values and give a bool (True or False): == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to) and >= (greater than or equal to). Remember that = assigns a value while == compares two values.

Comparisons can be chained: 1 < x < 10 means 1 < x and x < 10. This is called chaining, and it reads like maths.

The logical operators combine bools:

  • and is True only if both sides are True.
  • or is True if at least one side is True.
  • not flips True to False and False to True.

Python evaluates and and or lazily (short-circuit evaluation): in False and x, the right side is never evaluated, because the result is already known.

python
age = 16
print(age >= 13 and age <= 19)   # True
print(not age == 16)             # False
print(age < 13 or age > 65)      # False

Page 3

Operator precedence

Precedence decides which operator runs first when an expression has several. From highest to lowest:

  1. Parentheses ()
  2. Exponentiation **
  3. Unary minus, as in -x
  4. Multiplication, division, floor division and modulo: *, /, //, %
  5. Addition and subtraction: +, -
  6. Comparisons: ==, !=, <, >, <=, >=
  7. not
  8. and
  9. or

So and binds tighter than or. Operators with the same precedence are evaluated left to right, except ** which groups right to left: 2 ** 3 ** 2 is 2 ** 9, which is 512. Because ** binds tighter than unary minus, -2 ** 2 is -4, not 4. Use parentheses to make your intent clear: (-2) ** 2 is 4.

python
print(2 + 3 * 4)     # 14, not 20
print((2 + 3) * 4)   # 20
print(10 - 4 - 3)    # 3 (left to right)

Page 4

Strings: concatenation, repetition and f-strings

The + operator joins two strings; this is called concatenation: "snow" + "ball" gives "snowball". The * operator repeats a string, which is called repetition: "ha" * 3 gives "hahaha". You can't add a string and a number directly: "Score: " + 5 raises a TypeError, so convert the number with str() first.

An f-string is a string literal with an f before the opening quote. Expressions inside curly braces {} are evaluated and their values inserted into the string. F-strings were added in Python 3.6. A format specifier after a colon controls formatting: {price:.2f} shows a number with 2 decimal places.

python
name = "Ada"
score = 9.5
print(f"{name} scored {score}")   # Ada scored 9.5
print(f"Total: {2 * 3}")          # Total: 6
print(f"{3.14159:.2f}")           # 3.14
print("-" * 10)                   # ----------

Finished reading?

Mark it as read for +20 XP. Optional: practice is open either way.

Practice

Pass any one game to unlock Topic 4: Control Flow.

Sign in to play, save your best and unlock Topics.
  • Reach −1,500 m
  • Reach 150 km
  • 7/10 without falling
  • Clear both boards
  • 150 points

Learn more