NelsonLabs
Python Basics/Operators & Expressions

Operators & Expressions

Python's operators are similar to other languages but with some uniquely Pythonic additions โ€” particularly the exponentiation operator and integer division.

Arithmetic and comparison operators
python
# Arithmetic
10 + 3   # 13
10 - 3   # 7
10 * 3   # 30
10 / 3   # 3.3333...  (always float division)
10 // 3  # 3          (integer/floor division โ€” discard the decimal)
10 % 3   # 1          (modulo โ€” remainder)
2 ** 10  # 1024       (exponentiation โ€” 2 to the power of 10)

# Augmented assignment
count = 0
count += 5   # count = 5
count *= 2   # count = 10
count **= 2  # count = 100

# Comparison (return True or False)
5 == 5    # True
5 != 4    # True
5 >  3    # True
5 >= 5    # True
5 <  10   # True

# Python allows chained comparisons (unique feature)
1 < age < 100   # True if age is between 1 and 100
0 <= x <= 1     # True if x is between 0 and 1 inclusive
Logical and string operators
python
# Logical operators (Python uses words, not symbols)
True and False  # False
True or  False  # True
not True        # False

# Truthiness โ€” works in conditions
name    = "Nelson"
courses = ["Python", "Django"]

if name and courses:
    print("Has name and courses")

# String operators
"Hello" + " " + "World"   # "Hello World" (concatenation)
"ha" * 3                  # "hahaha" (repetition)
"ell" in "Hello"          # True (membership test โ€” very useful)
"xyz" not in "Hello"      # True

# Identity
x = [1, 2, 3]
y = x
x is y    # True โ€” same object in memory
x == y    # True โ€” same value

z = [1, 2, 3]
x is z    # False โ€” different objects (even though values match)
x == z    # True  โ€” same value