2.5 Operators
Overview of Python's various operators: arithmetic, assignment, comparison, logical, identity, and membership. Understanding them is essential for performing operations and creating logical conditions.
Arithmetic Operators
Used to perform basic mathematical operations.
a = 15
b = 4
print(f"Addition (+): {a + b}")
print(f"Subtraction (-): {a - b}")
print(f"Multiplication (*): {a * b}")
print(f"Division (/): {a / b}")
print(f"Floor Division (//): {a // b} (ignores the decimal part)")
print(f"Modulus (%): {a % b}")
print(f"Exponentiation (**): {a ** 2}")
Comparison & Logical Operators
Comparison operators (==, !=, >, <, >=, <=) compare two values and always return a Boolean value (`True` or `False`). Logical operators (`and`, `or`, `not`) combine Boolean expressions to create more complex conditions.
age = 25
has_license = True
is_adult = age >= 18
print(f"Is adult? {is_adult}")
print(f"Is adult AND has license? {is_adult and has_license}")
print(f"Is under 20 OR has license? {age < 20 or has_license}")
print(f"Is NOT adult? {not is_adult}")
Assignment Operators
These are shortcuts that perform an operation and assign the result back to the same variable. The basic operator is `=`, but there are others like `+=`, `-=`, `*=`, `/=`, etc.
counter = 5
counter += 2 # Equivalent to counter = counter + 2
print(f"After += 2, counter is: {counter}")
Identity (is, is not) and Membership (in, not in) Operators
These are more specialized operators. `is` checks if two variables refer to the exact same object in memory (not just if they have the same value). `in` checks if an element exists within a sequence (like a list or a string).
list_a = [1, 2, 3]
list_b = list_a # list_b points to the same object as list_a
list_c = [1, 2, 3] # list_c is a new, separate object
print(f"a is b: {list_a is list_b}") # True, because it's the same object in memory
print(f"a is c: {list_a is list_c}") # False, because they are different objects
print(f"a == c: {list_a == list_c}") # True, because their content is the same
my_list = ["apple", "banana", "cherry"]
print(f"'apple' in my_list: {'apple' in my_list}") # True
print(f"'pear' not in my_list: {'pear' not in my_list}") # True
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.