Chapter 4: Python Operators – Arithmetic, Comparison, Logical & More

Operators perform operations on variables and values. Python has 7 operator types.

1. Arithmetic Operators

Addition +

5 + 3  # 8

Subtraction -

10 - 2  # 8

Multiplication *

4 * 3  # 12

Division /

10 / 2  # 5.0 (float)

Modulus %

10 % 3  # 1 (remainder)

Exponentiation **

2 ** 3  # 8

Floor Division //

10 // 3  # 3 (integer division)

Exercise 1:

Calculate:

  1. (15 // 4) + (2 ** 3)
  2. The area of a circle with radius 7 (πr²)
import math
print((15 // 4) + (2 ** 3))  # 11
print(math.pi * 7 ** 2)      # 153.93804

2. Comparison Operators

Equal ==

5 == 5  # True

Not Equal !=

5 != 3  # True

Greater Than >

10 > 5  # True

Less Than <

10 < 5  # False

Greater/Equal >=

10 >= 10  # True

Less/Equal <=

5 <= 3  # False

Interactive Demo

5 == 3  # False

3. Logical Operators

AND and

True if both conditions are True

ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

OR or

True if at least one condition is True

ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

NOT not

Inverts the boolean value

Anot A
TrueFalse
FalseTrue

Exercise 2:

Given age = 25 and is_member = True, evaluate:

  1. age > 18 and is_member
  2. age < 21 or not is_member
age = 25
is_member = True
print(age > 18 and is_member)    # True
print(age < 21 or not is_member) # False

Operator Cheat Sheet

Type Operators Examples
Arithmetic + - * / % ** // 5 + 3 → 8
Comparison == != > < >= <= 5 > 3 → True
Logical and or not True and False → False
Assignment = += -= *= /= x += 5 (x = x + 5)
Membership in not in "a" in ["a","b"] → True