Python Operators
Performing Actions: Understanding Operators in Python
In your Python programs, you won't just store data in variables; you'll also need to do things with that data. You might need to perform mathematical calculations, compare values to see if they are the same or different, combine conditions, or check if a value is part of a collection.
How does Python know what action you want to perform? It uses operators. Without operators, your program would be like a list of ingredients (your data) without any instructions on how to mix or cook them.
What Are Operators?
Operators are special symbols or keywords in Python that tell the computer to perform a specific action on one or more values or variables.
The values or variables that the operator acts upon are called operands.
# In this example:
# '+' is the operator
# '10' and '5' are the operands
result = 10 + 5
Python has different types of operators for different jobs. Let's look at the most common categories.
Arithmetic Operators
These operators are used to perform common mathematical calculations with numbers (integers and floats).
Addition (+
)
Adds two operands.
sum_result = 10 + 5
print(sum_result) # Output: 15
float_sum = 3.5 + 2.0
print(float_sum) # Output: 5.5
Subtraction (-
)
Subtracts the second operand from the first.
diff_result = 10 - 5
print(diff_result) # Output: 5
float_diff = 3.5 - 1.5
print(float_diff) # Output: 2.0
Multiplication (*
)
Multiplies two operands.
prod_result = 10 * 5
print(prod_result) # Output: 50
float_prod = 2.5 * 4.0
print(float_prod) # Output: 10.0
Division (/
)
Divides the first operand by the second. Important: Standard division (/
) always results in a float
number, even if the result is a whole number.
div_result1 = 10 / 5
print(div_result1) # Output: 2.0 (This is a float!)
div_result2 = 10 / 3
print(div_result2) # Output: 3.3333333333333335
Integer Division (//
)
Divides the first operand by the second and returns the largest whole number (integer) less than or equal to the result. It discards the decimal part.
int_div_result1 = 10 // 3
print(int_div_result1) # Output: 3
int_div_result2 = 11 // 4
print(int_div_result2) # Output: 2
# Can also work with floats, result will be a float whole number
float_int_div = 10.5 // 3.2
print(float_int_div) # Output: 3.0
Modulo (%
)
Returns the remainder left after dividing the first operand by the second.
remainder1 = 10 % 3 # 10 divided by 3 is 3 with a remainder of 1
print(remainder1) # Output: 1
remainder2 = 12 % 4 # 12 divided by 4 is 3 with a remainder of 0
print(remainder2) # Output: 0
Exponentiation (**
)
Raises the first operand to the power of the second operand.
power_result1 = 2 ** 3 # 2 to the power of 3 (2 * 2 * 2)
print(power_result1) # Output: 8
power_result2 = 9 ** 0.5 # 9 to the power of 0.5 (square root of 9)
print(power_result2) # Output: 3.0
Comparison Operators
These operators are used to compare two values. They always return a boolean value: True
or False
.
Equal to (==
)
Checks if the values of two operands are equal. Remember: This is different from the single equals sign (=
) which is used for assignment!
is_equal1 = (5 == 5)
print(is_equal1) # Output: True
is_equal2 = (5 == 10)
print(is_equal2) # Output: False
is_equal3 = ("Hello" == "hello")
print(is_equal3) # Output: False (Case matters!)
Not equal to (!=
)
Checks if the values of two operands are not equal.
is_not_equal1 = (5 != 10)
print(is_not_equal1) # Output: True
is_not_equal2 = (5 != 5)
print(is_not_equal2) # Output: False
Greater than (>
)
Checks if the left operand is greater than the right operand.
is_greater1 = (10 > 5)
print(is_greater1) # Output: True
is_greater2 = (5 > 10)
print(is_greater2) # Output: False
Less than (<
)
Checks if the left operand is less than the right operand.
is_less1 = (5 < 10)
print(is_less1) # Output: True
is_less2 = (10 < 5)
print(is_less2) # Output: False
Greater than or equal to (>=
)
Checks if the left operand is greater than or equal to the right operand.
is_ge1 = (10 >= 10)
print(is_ge1) # Output: True
is_ge2 = (10 >= 5)
print(is_ge2) # Output: True
Less than or equal to (<=
)
Checks if the left operand is less than or equal to the right operand.
is_le1 = (5 <= 5)
print(is_le1) # Output: True
is_le2 = (5 <= 10)
print(is_le2) # Output: True
Logical Operators
These operators are used to combine boolean values (True
or False
) or "truthy"/"falsy" values (as discussed in the Data Types article) and give a single boolean result. They are fundamental for making decisions in your code.
and
Returns True
if both operands are true (or truthy). Otherwise, returns False
.
is_adult = True
has_ticket = True
can_enter = is_adult and has_ticket
print(can_enter) # Output: True
is_student = False
is_under_18 = True
gets_discount = is_student and not is_under_18 # Example with not
print(gets_discount) # Output: False
or
Returns True
if at least one of the operands is true (or truthy). Otherwise, returns False
.
has_coupon = False
is_vip = True
gets_special_offer = has_coupon or is_vip
print(gets_special_offer) # Output: True
is_weekend = False
is_holiday = False
go_play = is_weekend or is_holiday
print(go_play) # Output: False
not
Reverses the logical state of the operand. not True
becomes False
, and not False
becomes True
.
is_sunny = False
is_rainy = not is_sunny
print(is_rainy) # Output: True
is_empty_list = not [] # Empty list is falsy, not makes it True
print(is_empty_list) # Output: True
Assignment Operators
You already saw the basic assignment operator (=
) in the Variables article. Assignment operators are used to give values to variables.
Simple Assignment (=
)
Assigns the value on the right to the variable name on the left.
my_variable = 100
Combined Assignment Operators
These are shortcuts that combine an arithmetic operation with assignment. They perform the operation on the variable and the value, then assign the result back to the variable.
# Add AND Assign
count = 10
count += 5 # This is a shortcut for: count = count + 5
print(count) # Output: 15
# Subtract AND Assign
lives = 3
lives -= 1 # Shortcut for: lives = lives - 1
print(lives) # Output: 2
# Multiply AND Assign
price = 20
price *= 0.8 # Apply 20% discount (price = price * 0.8)
print(price) # Output: 16.0
# Divide AND Assign
total = 100
total /= 4 # total = total / 4
print(total) # Output: 25.0
Other combined assignment operators include //=
, %=
, and **=
.
Identity Operators
These operators check if two variable names point to the exact same object in the computer's memory. They return True
or False
. They are different from comparison operators (==
) which check if the values are the same.
is
Returns True
if the two operands refer to the same object.
list1 = [1, 2, 3]
list2 = [1, 2, 3] # This is a *new* list object, even though it has the same values
list3 = list1 # This makes list3 point to the *same* list object as list1
print(list1 is list2) # Output: False (They are different objects)
print(list1 is list3) # Output: True (They point to the same object)
is not
Returns True
if the two operands do not refer to the same object.
a = 10
b = 10 # Python often reuses small immutable objects like numbers
c = 20
print(a is not c) # Output: True (10 and 20 are different objects)
print(a is not b) # Output: False (Often, small integers like 10 are the *same* object)
is
vs. ==
(Identity vs. Equality)
This is a common point of confusion!
==
checks for equality: Do the objects have the same value?is
checks for identity: Are they the exact same object in memory?
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(list1 == list2) # Output: True (Their values are the same)
print(list1 is list2) # Output: False (But they are different objects in memory)
print(list1 == list3) # Output: True (Same value, same object)
print(list1 is list3) # Output: True (Same value, same object)
Always use ==
or !=
when you want to compare if two objects have the same value. Use is
or is not
only when you specifically need to check if two names are pointing to the exact same object in memory (this is less common for beginners, but important for understanding).
Membership Operators
These operators are used to check if a value is found within a sequence or collection (like a string, list, tuple, set, or dictionary keys). They return True
or False
.
in
Returns True
if the value is found in the sequence.
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # Output: True
print("grape" in fruits) # Output: False
message = "Hello World"
print("World" in message) # Output: True (Checks for substring)
print("hello" in message) # Output: False (Case sensitive)
student_scores = {"Alice": 85, "Bob": 92}
print("Alice" in student_scores) # Output: True (Checks if key exists)
print(85 in student_scores.values()) # Output: True (Need .values() to check values)
not in
Returns True
if the value is not found in the sequence.
numbers = [1, 2, 3, 4]
print(5 not in numbers) # Output: True
print(3 not in numbers) # Output: False
Operator Precedence (Order of Operations)
Just like in mathematics, operators in Python have an order in which they are processed. This is called operator precedence. For example, multiplication and division usually happen before addition and subtraction.
result = 5 + 2 * 3
# Multiplication (2 * 3) happens first, then addition.
# result = 5 + 6
# result = 11
print(result) # Output: 11
You can use parentheses ()
to change the order of operations. Anything inside parentheses is calculated first.
result_with_parens = (5 + 2) * 3
# Parentheses (5 + 2) happen first, then multiplication.
# result_with_parens = 7 * 3
# result_with_parens = 21
print(result_with_parens) # Output: 21
If you're unsure about the order, using parentheses is always a good idea to make your code clearer.
Operator Overloading (Doing Different Things)
You might notice that some operators, like +
or *
, can behave differently depending on the types of the operands they are used with.
# With numbers, '+' means addition:
print(10 + 5) # Output: 15
# With strings, '+' means joining (concatenation):
print("Hello" + "World") # Output: HelloWorld
# With numbers, '*' means multiplication:
print(5 * 3) # Output: 15
# With a string and an integer, '*' means repetition:
print("Python" * 3) # Output: PythonPythonPython
# With lists, '+' means joining lists:
print([1, 2] + [3, 4]) # Output: [1, 2, 3, 4]
This ability for an operator to perform different actions based on the data types it's used with is called operator overloading. Python's built-in types define how operators work for them. This makes the language flexible and intuitive for common operations across different data types.
Conclusion
Operators are the action words of Python. They allow you to perform calculations, compare values, combine logical conditions, manage variable assignments, check object identity, and look for membership within collections.
You've explored the main categories: Arithmetic, Comparison, Logical, Assignment, Identity, and Membership operators. You've also seen how operators follow a specific order (precedence) and how some operators can do different jobs depending on the data types involved (overloading).
Understanding operators is essential because they are used in almost every line of code to manipulate and evaluate data. Practice using different operators with the variable types you learned about previously.
Now that you understand how to store data (Variables) and perform actions on it (Operators), you're ready to learn how your programs can interact with the outside world: taking in information from the user and showing results using Inputs and Outputs.