Lesson 3 / 11

Operators and Expressions

Operators combine values into expressions, and Python groups them into a few families you’ll use constantly in almost every program you write.

Arithmetic

7 + 3    # 10
7 - 3    # 4
7 * 3    # 21
7 / 3    # 2.333... (always returns a float)
7 // 3   # 2  (floor division -- rounds down to the nearest whole number)
7 % 3    # 1  (remainder, also called the modulo operator)
7 ** 2   # 49 (power, i.e. 7 squared)

The distinction between / and // trips up a lot of beginners: regular division always returns a float, even when the numbers divide evenly (10 / 2 gives 5.0, not 5). Floor division always rounds down toward negative infinity, which matters for negative numbers: -7 // 2 gives -4, not -3.

Comparison

5 == 5   # True  (equal to)
5 != 3   # True  (not equal to)
5 > 3    # True
5 <= 4   # False

Note the double equals sign == for comparison versus a single = for assignment — mixing these up is one of the most common bugs in any language, and Python will usually catch it for you with a syntax error if you try to use = where a comparison is expected.

Logical operators

age = 20
has_id = True
can_enter = age >= 18 and has_id   # True

is_weekend = False
is_holiday = True
day_off = is_weekend or is_holiday   # True

is_banned = not False   # True

and, or, and not combine boolean expressions — you’ll use these constantly once you get to conditionals in the next lesson. Python also short-circuits: in a and b, if a is already False, Python never even evaluates b, which is a useful behavior once you start writing conditions that call functions.

Assignment shortcuts

score = 10
score += 5   # same as: score = score + 5, now 15
score -= 3   # now 12
score *= 2   # now 24

These compound assignment operators are shorthand, not a different feature — they save you from repeating the variable name on both sides of an assignment, and you’ll see them used heavily in loops.