Now that we know how to store data using variables, it's time to learn how to manipulate that data. This is where operators come in! Operators are special symbols that perform operations on one or more operands (variables or values). Think of them as the verbs of your Python code, telling the computer what actions to perform.
Python offers a variety of operators, each with its own purpose. We'll explore the most common ones here, starting with arithmetic operators.
Arithmetic Operators: These are used for mathematical calculations.
a = 10
b = 5
# Addition
print(a + b) # Output: 15
# Subtraction
print(a - b) # Output: 5
# Multiplication
print(a * b) # Output: 50
# Division
print(a / b) # Output: 2.0 (Note: always returns a float)
# Floor Division (integer division)
print(a // b) # Output: 2 (Discards the fractional part)
# Modulus (remainder of division)
print(a % b) # Output: 0
# Exponentiation (power)
print(a ** 2) # Output: 100 (10 to the power of 2)Comparison Operators: These are used to compare values and return a boolean result (True or False).
x = 7
y = 12
# Equal to
print(x == y) # Output: False
# Not equal to
print(x != y) # Output: True
# Greater than
print(x > y) # Output: False
# Less than
print(x < y) # Output: True
# Greater than or equal to
print(x >= y) # Output: False
# Less than or equal to
print(x <= y) # Output: TrueLogical Operators: These are used to combine conditional statements. They also return boolean values.
p = True
q = False
# AND (returns True if both operands are True)
print(p and q) # Output: False
# OR (returns True if at least one operand is True)
print(p or q) # Output: True
# NOT (reverses the boolean value)
print(not p) # Output: FalseAssignment Operators: These are used to assign values to variables. While the '=' operator is the most common, there are shorthand versions that combine an arithmetic operation with assignment.