Lesson 3 of 2020 min read

Operators and Expressions

Share:WhatsAppLinkedIn

Prerequisites: Variables and Data Types (an earlier lesson)


1. What Are Operators and Expressions?

  • Operator: A symbol that performs an operation on one or more values (operands)
  • Operand: The value(s) on which the operator acts
  • Expression: A combination of values, variables, and operators that evaluates to a single value
# In the expression: 5 + 3
# 5 and 3 are operands
# + is the operator
# The expression evaluates to 8

Python has 7 types of operators.


2. Arithmetic Operators

Operator Name Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division (true) 7 / 2 3.5
// Floor Division 7 // 2 3
% Modulus (remainder) 7 % 2 1
** Exponentiation (power) 2 ** 3 8
# Example 1: Basic arithmetic
print(10 + 3) # 13
print(10 - 3) # 7
print(10 * 3) # 30
print(10 / 3) # 3.3333333333333335
print(10 // 3) # 3
print(10 % 3) # 1
print(10 ** 3) # 1000

Output:

13
7
30
3.3333333333333335
3
1
1000

Division (/) vs Floor Division (//)

This is one of the most commonly tested concepts.

# Example 2: / vs //
print(7 / 2) # 3.5 (true division, always returns float)
print(7 // 2) # 3 (floor division, rounds DOWN to nearest integer)
print(7.0 / 2) # 3.5
print(7.0 // 2) # 3.0 (floor division with float operand gives float result)

# CRITICAL: Floor division with negative numbers
print(-7 / 2) # -3.5
print(-7 // 2) # -4 (NOT -3! Rounds DOWN toward negative infinity)
print(7 // -2) # -4 (same: rounds DOWN)

# This is the most common exam trick!
print(-13 // 4) # -4 (not -3)
print(13 // -4) # -4 (not -3)

Output:

3.5
3
3.5
3.0
-3.5
-4
-4
-4
-4

Why -7 // 2 = -4? Floor division always rounds down (toward negative infinity). -3.5 rounded down is -4, not -3. The mathematical floor function: floor(-3.5) = -4.

Modulus (%) with Negative Numbers

# Example 3: Modulus with negative numbers
print(7 % 2) # 1 (7 = 2*3 + 1)
print(-7 % 2) # 1 (NOT -1! Result has same sign as divisor)
print(7 % -2) # -1 (result has same sign as divisor, which is -2)
print(-7 % -2) # -1

# Formula: a % b = a - (a // b) * b
# -7 % 2 = -7 - (-7 // 2) * 2 = -7 - (-4) * 2 = -7 + 8 = 1

Output:

1
1
-1
-1

Exponentiation (**), Right-to-Left Associativity

# Example 4: Power operator
print(2 ** 3) # 8
print(3 ** 2) # 9

# Right-to-left associativity (IMPORTANT!)
print(2 ** 3 ** 2) # 512 (NOT 64!)
# Evaluated as: 2 ** (3 ** 2) = 2 ** 9 = 512
# NOT as: (2 ** 3) ** 2 = 8 ** 2 = 64

Output:

8
9
512

String and List Operations with + and *

# Example 5: + and * with strings and lists
print("Hello" + " " + "World") # Hello World (concatenation)
print("Ha" * 3) # HaHaHa (repetition)
print([1, 2] + [3, 4]) # [1, 2, 3, 4] (list concatenation)
print([0] * 5) # [0, 0, 0, 0, 0] (list repetition)

# Cannot add string and number
# print("Age: " + 25) # TypeError!
print("Age: " + str(25)) # Age: 25 (convert to string first)

Output:

Hello World
HaHaHa
[1, 2, 3, 4]
[0, 0, 0, 0, 0]
Age: 25

3. Relational (Comparison) Operators

These operators compare two values and return a boolean result (True or False).

Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
< Less than 3 < 5 True
> Greater than 5 > 3 True
<= Less than or equal 5 <= 5 True
>= Greater than or equal 5 >= 6 False
# Example 6: Relational operators
a = 10
b = 20
print(a == b) # False
print(a != b) # True
print(a < b) # True
print(a > b) # False
print(a <= 10) # True
print(a >= 15) # False

Output:

False
True
True
False
True
False

String Comparison (Lexicographic / Dictionary Order)

Strings are compared character by character using their ASCII/Unicode values.

# Example 7: String comparison
print("apple" == "apple") # True
print("apple" == "Apple") # False (case-sensitive! 'a' != 'A')
print("apple" < "banana") # True ('a' < 'b' in ASCII)
print("abc" < "abd") # True (first two chars same, 'c' < 'd')
print("abc" < "abcd") # True (shorter string is "less" when prefix matches)
print("B" < "a") # True (uppercase letters have smaller ASCII values)

# ASCII values: A=65, B=66, ..., Z=90, a=97, b=98, ..., z=122
print(ord("A")) # 65
print(ord("a")) # 97
print(ord("0")) # 48

Output:

True
False
True
True
True
True
65
97
48

Chained Comparisons

Python allows chaining comparisons, a unique feature!

# Example 8: Chained comparisons
x = 15
print(10 < x < 20) # True (same as: 10 < x and x < 20)
print(1 < 2 < 3 < 4) # True
print(10 < x > 5) # True (10 < x and x > 5)
print(1 < 2 > 3) # False (1 < 2 is True, but 2 > 3 is False)

Output:

True
True
True
False

4. Logical Operators

Operator Description Example
and True if both are True True and True = True
or True if at least one is True True or False = True
not Reverses the boolean not True = False

Truth Table

A B A and B A or B not A
True True True True False
True False False True False
False True False True True
False False False False True
# Example 9: Logical operators
a = True
b = False

print(a and b) # False
print(a or b) # True
print(not a) # False
print(not b) # True

# With expressions
x = 10
print(x > 5 and x < 20) # True (both conditions true)
print(x > 5 and x < 8) # False (second condition false)
print(x < 5 or x > 8) # True (second condition true)
print(not x > 5) # False (x > 5 is True, not True = False)

Output:

False
True
False
True
True
False
True
False

Short-Circuit Evaluation (IMPORTANT!)

Python does not evaluate the second operand if the result can be determined from the first.

  • and: If the first operand is False, the result is False regardless, second operand is NOT evaluated
  • or: If the first operand is True, the result is True regardless, second operand is NOT evaluated
# Example 10: Short-circuit evaluation
# and: stops at first False
print(False and print("This won't print")) # False (print not executed)

# or: stops at first True
print(True or print("This won't print")) # True (print not executed)

What and / or actually return (Python-specific behavior):

Python's and and or do not always return True/False. They return one of the operands:

  • and: Returns first falsy value, or last value if all truthy
  • or: Returns first truthy value, or last value if all falsy
# Example 11: Actual return values of and/or
print(5 and 10) # 10 (both truthy, returns last)
print(0 and 10) # 0 (first is falsy, returns it)
print("" and "hello") # "" (first is falsy)

print(5 or 10) # 5 (first is truthy, returns it)
print(0 or 10) # 10 (first is falsy, second is truthy)
print(0 or "" or []) # [] (all falsy, returns last)
print(0 or "" or 5) # 5 (first truthy value)

Output:

10
0

5
10
[]
5

Truthy and Falsy Values

In Python, every value has a boolean interpretation:

Falsy values (evaluate to False): 0, 0.0, "" (empty string), [] (empty list), `` (empty tuple), {} (empty dict), set (empty set), None, False

Truthy values (evaluate to True): Everything else (non-zero numbers, non-empty strings/collections, True)

# Example 12: Truthy and Falsy
print(bool(0)) # False
print(bool(42)) # True
print(bool(-1)) # True (any non-zero number)
print(bool("")) # False
print(bool("Hi")) # True
print(bool([])) # False
print(bool([1, 2])) # True
print(bool(None)) # False

Output:

False
True
True
False
True
False
True
False

5. Assignment Operators

Operator Equivalent to Example
= Direct assignment x = 10
+= x = x + value x += 5 (x becomes 15)
-= x = x - value x -= 3 (x becomes 12)
*= x = x * value x *= 2 (x becomes 24)
/= x = x / value x /= 4 (x becomes 6.0)
//= x = x // value x //= 2 (x becomes 3.0)
%= x = x % value x %= 2 (x becomes 1.0)
**= x = x ** value x **= 3 (x becomes 1.0)
# Example 13: Assignment operators
x = 10
print(x) # 10

x += 5 # x = x + 5
print(x) # 15

x -= 3 # x = x - 3
print(x) # 12

x *= 2 # x = x * 2
print(x) # 24

x //= 5 # x = x // 5
print(x) # 4

x **= 3 # x = x ** 3
print(x) # 64

x %= 10 # x = x % 10
print(x) # 4

Output:

10
15
12
24
4
64
4

Note: Python does NOT have ++ or -- operators (unlike C/Java). Use x += 1 and x -= 1 instead.


6. Identity Operators

Identity operators check whether two variables refer to the same object in memory (same id), not just the same value.

Operator Meaning
is True if both variables refer to same object
is not True if both variables refer to different objects
# Example 14: Identity operators
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b) # True (same value)
print(a is b) # False (different objects in memory!)
print(a is c) # True (c points to the same object as a)
print(a is not b) # True

print(id(a)) # e.g., 140234866001280
print(id(b)) # e.g., 140234866002340 (different!)
print(id(c)) # same as id(a)

Output:

True
False
True
True

== vs is: == checks if values are equal. is checks if they are the same object in memory.

# Special case with small integers (Python caches -5 to 256)
x = 10
y = 10
print(x is y) # True (Python caches small integers)

x = 1000
y = 1000
print(x is y) # May be False (not cached)

7. Membership Operators

Check if a value exists in a sequence (string, list, tuple, dict, set).

Operator Meaning
in True if value found in sequence
not in True if value NOT found in sequence
# Example 15: Membership operators

# In strings
print("H" in "Hello") # True
print("h" in "Hello") # False (case-sensitive!)
print("ell" in "Hello") # True (substring check)
print("xyz" not in "Hello") # True

# In lists
marks = [85, 92, 78, 95]
print(92 in marks) # True
print(100 in marks) # False
print(100 not in marks) # True

# In tuples
colors = ("red", "green", "blue")
print("red" in colors) # True
print("yellow" in colors) # False

# In dictionaries (checks KEYS, not values!)
student = {"name": "Priya", "age": 16}
print("name" in student) # True (key exists)
print("Priya" in student) # False (checks keys, not values!)
print(16 in student) # False (checks keys, not values!)

Output:

True
False
True
True
True
False
True
True
False
True
False
False

8. Bitwise Operators (Brief)

These operate on the binary representation of integers. Less frequently tested but good to know.

Operator Name Example Result
& AND 5 & 3 1
| OR 5 | 3 7
^ XOR 5 ^ 3 6
~ NOT (complement) ~5 -6
<< Left shift 5 << 1 10
>> Right shift 5 >> 1 2
# Example 16: Bitwise operators
# 5 in binary: 101
# 3 in binary: 011

print(5 & 3) # 1 (binary: 101 & 011 = 001)
print(5 | 3) # 7 (binary: 101 | 011 = 111)
print(5 ^ 3) # 6 (binary: 101 ^ 011 = 110)
print(~5) # -6 (inverts all bits, formula: -(n+1))
print(5 << 1) # 10 (binary: 101 becomes 1010, multiply by 2)
print(5 >> 1) # 2 (binary: 101 becomes 10, divide by 2)

Output:

1
7
6
-6
10
2

Quick rule: Left shift by n = multiply by 2^n. Right shift by n = integer divide by 2^n.


9. Operator Precedence Table

When an expression has multiple operators, Python evaluates them in a specific order of precedence (priority). Higher precedence operators are evaluated first.

Priority Operator Description Associativity
1 (highest) `` Parentheses Left to right
2 ** Exponentiation Right to left
3 ~, +x, -x Unary NOT, positive, negative Right to left
4 *, /, //, % Multiply, Divide, Floor div, Modulus Left to right
5 +, - Addition, Subtraction Left to right
6 <<, >> Bitwise shifts Left to right
7 & Bitwise AND Left to right
8 ^ Bitwise XOR Left to right
9 | Bitwise OR Left to right
10 ==, !=, <, >, <=, >=, is, is not, in, not in Comparisons Left to right
11 not Logical NOT Right to left
12 and Logical AND Left to right
13 (lowest) or Logical OR Left to right

Memory aid: P E U MD AS (Parentheses, Exponentiation, Unary, Multiplication/Division, Addition/Subtraction) for arithmetic, then Comparisons, then not, then and, then or.


10. Expression Evaluation Examples (Step by Step)

These are the most common "find the output" questions in exams.

# Example 17: Step-by-step evaluation

# Expression 1: 2 + 3 * 4 - 1
# Step 1: 3 * 4 = 12 (multiplication first)
# Step 2: 2 + 12 = 14 (addition)
# Step 3: 14 - 1 = 13 (subtraction)
print(2 + 3 * 4 - 1) # 13

# Expression 2: 2 ** 3 ** 2
# Step 1: 3 ** 2 = 9 (right-to-left for **)
# Step 2: 2 ** 9 = 512
print(2 ** 3 ** 2) # 512

# Expression 3: 15 // 4 + 15 % 4
# Step 1: 15 // 4 = 3 (floor division)
# Step 2: 15 % 4 = 3 (modulus)
# Step 3: 3 + 3 = 6
print(15 // 4 + 15 % 4) # 6

# Expression 4: 5 + 10 * 3 // 2 - 1
# Step 1: 10 * 3 = 30 (multiplication)
# Step 2: 30 // 2 = 15 (floor division, same precedence as *, left-to-right)
# Step 3: 5 + 15 = 20 (addition)
# Step 4: 20 - 1 = 19 (subtraction)
print(5 + 10 * 3 // 2 - 1) # 19

# Expression 5: (5 + 3) * 2 ** 2 / 4
# Step 1: (5 + 3) = 8 (parentheses first)
# Step 2: 2 ** 2 = 4 (exponentiation)
# Step 3: 8 * 4 = 32 (multiplication)
# Step 4: 32 / 4 = 8.0 (true division gives float)
print((5 + 3) * 2 ** 2 / 4) # 8.0

Output:

13
512
6
19
8.0
# Example 18: Mixed expressions with logical and relational operators

# Expression 6: not 5 > 3 and 2 < 4
# Step 1: 5 > 3 = True (comparison)
# Step 2: 2 < 4 = True (comparison)
# Step 3: not True = False (not has higher precedence than and)
# Step 4: False and True = False (and)
print(not 5 > 3 and 2 < 4) # False

# Expression 7: 3 > 2 or 5 < 1 and 4 > 3
# Step 1: 3 > 2 = True (comparison)
# Step 2: 5 < 1 = False (comparison)
# Step 3: 4 > 3 = True (comparison)
# Step 4: False and True = False (and before or)
# Step 5: True or False = True (or)
print(3 > 2 or 5 < 1 and 4 > 3) # True

# Expression 8: not True or False and True
# Step 1: not True = False (not first)
# Step 2: False and True = False (and before or)
# Step 3: False or False = False (or)
print(not True or False and True) # False

Output:

False
True
False
# Example 19: More tricky expressions

# Expression 9: 10 > 5 and 20 > 10 or 5 > 20
# Step 1: 10 > 5 = True
# Step 2: 20 > 10 = True
# Step 3: 5 > 20 = False
# Step 4: True and True = True (and before or)
# Step 5: True or False = True
print(10 > 5 and 20 > 10 or 5 > 20) # True

# Expression 10: 15 / 4 + 15 // 4 + 15 % 4
# Step 1: 15 / 4 = 3.75
# Step 2: 15 // 4 = 3
# Step 3: 15 % 4 = 3
# Step 4: 3.75 + 3 = 6.75
# Step 5: 6.75 + 3 = 9.75
print(15 / 4 + 15 // 4 + 15 % 4) # 9.75

# Expression 11: 2 * 3 + 4 % 5 - 2 // 3 + 6
# Step 1: 2 * 3 = 6
# Step 2: 4 % 5 = 4
# Step 3: 2 // 3 = 0
# Step 4: 6 + 4 = 10
# Step 5: 10 - 0 = 10
# Step 6: 10 + 6 = 16
print(2 * 3 + 4 % 5 - 2 // 3 + 6) # 16

# Expression 12: "Hello" + "World" == "HelloWorld"
print("Hello" + "World" == "HelloWorld") # True

# Expression 13: 10 == 10.0
print(10 == 10.0) # True (Python compares values, not types)
print(10 is 10.0) # False (different types = different objects)

Output:

True
9.75
16
True
True
False
# Example 20: Expressions with membership and identity

name = "Python"
langs = ["Python", "Java", "C++"]

print("P" in name) # True
print("python" in name) # False (case-sensitive)
print("Python" in langs) # True
print("Ruby" not in langs) # True
print(type(10) is int) # True
print(type("hi") is not int) # True

Output:

True
False
True
True
True
True

Common Mistakes

  1. -7 // 2 = -4, not -3: Floor division rounds toward negative infinity, not toward zero
  2. -7 % 2 = 1, not -1: The result of % has the same sign as the divisor (right operand)
  3. 2 ** 3 ** 2 = 512, not 64: ** is right-to-left associative
  4. / always returns float: 6 / 3 = 2.0, not 2
  5. Confusing = and ==: x = 5 assigns; x == 5 compares
  6. Confusing is and ==: [1,2] == [1,2] is True but [1,2] is [1,2] is False
  7. Forgetting not has higher precedence than and: not True and False = False and False = False
  8. in with dictionaries checks keys: "value" in {"key": "value"} is False
  9. Assuming and/or always return True/False: 5 and 10 returns 10, not True
  10. Operator precedence with unary minus: -2 ** 2 = -4 (not 4), because ** has higher precedence than unary -. It is evaluated as -(2 ** 2) = -4
  11. String comparison is case-sensitive: "apple" < "Banana" is False because 'a' (97) > 'B' (66)
  12. No ++ or -- in Python: Use x += 1 and x -= 1
  13. Chained assignment confusion: a = b = 5 assigns 5 to both; a = b = [] makes both point to the SAME list

$1$2 Quick Tips

  1. Expression evaluation (2-4 marks): The single most common question type. Practice solving step-by-step, showing which operator is evaluated first
  2. Operator precedence order (1-2 marks): Memorize the table, especially ** > * / // % > + - > comparisons > not > and > or
  3. Difference between / and // (2 marks): / gives float (always); // gives floor of division. Show with positive and negative numbers
  4. Difference between == and is (2 marks): == checks value equality; is checks identity (same object in memory)
  5. Short-circuit evaluation (2 marks): Explain with examples of and and or
  6. % and // with negative numbers (2 marks): Very tricky; know the formulas and show step-by-step
  7. in and not in questions (1-2 marks): String membership, list membership, dict key checking
  8. Logical operator truth tables (1-2 marks): Draw and fill the truth table for and, or, not
  9. Associativity of ** (1-2 marks): Right-to-left; 2**3**2 = 512
  10. Augmented assignment (1 mark): What does x *= 3 mean? (same as x = x * 3)

Test Your Knowledge

Take a quick quiz on this lesson

Start Quiz →

Prefer watching over reading?

Subscribe for free.

Subscribe on YouTube