Operators are the symbols that perform operations on variables and values. In Python, these are very similar to C, but with a few extra "superpowers" that make math and logic much simpler.
1. Categories of Operators
Category. Operators. Description
Arithmetic+, -, *, /, //, %, **Standard math + Floor division and Exponentiation.
Comparison==, !=, >, <, >=, <=Returns True or False.
Logicaland, or, notUsed to combine conditional statements.
Assignment=, +=, -=, *=, /=Assigns values to variables.
Membershipin, not inChecks if a value exists in a sequence (like a list).
2. Special Python Operators
Unlike C, Python includes a few specific operators for common tasks:
Floor Division (
//): Divides and rounds down to the nearest whole number.Exponentiation (
**): Calculates power (e.g., $2^{3}$ is written as2 ** 3).Logical Words: Python uses the actual words
and,or, andnotinstead of symbols like&&,||, and!.
# Arithmetic
print(10 / 3) # Normal division: 3.3333...
print(10 // 3) # Floor division: 3
print(2 ** 3) # Exponent (2 cubed): 8
# Logical Operators
age = 20
has_license = True
if age >= 18 and has_license:
print("You can drive!")
# Membership Operators
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("orange" not in fruits) # True3. Expressions and Precedence
An expression is a combination of values and operators that evaluates to a single value. Python follows the PEMDAS rule (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction).
result = 10 + 5 * 2 ** 2 # 5 * 4 = 20, then + 10 = 30
print(result)