python-course-chapter-05
Chapter 5: Python Operators
Learn arithmetic, assignment, comparison, logical, identity, membership, bitwise, precedence, and special Python operators.
Goal: Understand how Python operators work, read their results, and combine them in practical beginner programs.
5.1 What Are Operators?
Operators are special symbols or words that tell Python to perform an action with one or more values. For example, the plus sign adds numbers, while comparison operators check whether values are equal or different. Understanding operators is important because calculations, decisions, searches, and many other programming tasks depend on them.
Example: What Are Operators?
# Store two numbers.
first_number = 8
second_number = 3
# Use the addition operator.
result = first_number + second_number
# Show the result.
print(result)
Output Explanation: The plus sign is the operator. The numbers stored in first_number and second_number are the values used by the operator. Python adds 8 and 3, stores the answer in result, and print() displays 11.
5.2 Operands
Operands are the values or variables on which an operator works. In the expression 10 + 5, the numbers 10 and 5 are operands, while the plus sign is the operator. Operands can be numbers, strings, variables, lists, or other Python objects, depending on what the selected operator supports.
Example: Operands
# These two variables are operands.
price = 20
quantity = 4
# The multiplication operator works on both operands.
total = price * quantity
print(total)
Output Explanation: The variables price and quantity are operands because the multiplication operator uses their values. Python multiplies 20 by 4 and stores 80 in total. The print() function then displays the final value.
5.3 Arithmetic Operators
Arithmetic operators perform mathematical calculations. Python includes operators for addition, subtraction, multiplication, regular division, floor division, remainder, and powers. These operators are useful for totals, prices, measurements, scores, ages, and many other number-based tasks. Python follows mathematical precedence rules when several arithmetic operators appear in one expression.
Example: Arithmetic Operators
a = 12
b = 5
print(a + b)
print(a - b)
print(a * b)
print(a / b)
Output Explanation: Each line uses a different arithmetic operator. Python adds, subtracts, multiplies, and divides the same two values. Regular division uses the slash operator and produces 2.4, which is a floating-point number.
5.4 Addition
The addition operator uses the plus sign to combine numeric values. It can add integers, decimal numbers, and compatible numeric types. The plus sign can also join strings, although that is called concatenation rather than mathematical addition. Beginners often use addition to calculate totals, scores, distances, ages, and shopping costs.
Example: Addition
# Prices of two items.
book_price = 12
pen_price = 3
# Add both prices.
total_price = book_price + pen_price
print(total_price)
Output Explanation: Python reads the values 12 and 3 and adds them with the plus operator. The result, 15, is stored in total_price. Printing the variable shows the combined cost of the book and pen.
5.5 Subtraction
The subtraction operator uses the minus sign to remove one number from another. It is useful for calculating change, remaining quantities, differences, losses, and distances. The order of operands matters because subtracting 3 from 10 is different from subtracting 10 from 3. Python evaluates subtraction from left to right.
Example: Subtraction
money = 50
cost = 18
# Subtract the cost from the money.
remaining_money = money - cost
print(remaining_money)
Output Explanation: Python subtracts the cost, 18, from the original amount, 50. The remaining value is 32. Because subtraction depends on order, money must appear before cost to calculate how much money remains.
5.6 Multiplication
The multiplication operator uses an asterisk to multiply numbers. It is commonly used to calculate repeated quantities, areas, prices, distances, and totals. In Python, an asterisk is used instead of the multiplication symbol seen in school mathematics. Multiplication can also repeat strings when a string is multiplied by an integer.
Example: Multiplication
item_price = 7
number_of_items = 6
# Multiply price by quantity.
total_cost = item_price * number_of_items
print(total_cost)
Output Explanation: The asterisk multiplies 7 by 6. Python stores the result, 42, in total_cost. This example shows a common real-world use: calculating the total cost when several items have the same price.
5.7 Division
The regular division operator uses a forward slash. It divides the left operand by the right operand and normally returns a floating-point result, even when the answer is a whole number. Division is useful for averages, equal sharing, rates, percentages, and measurements. Dividing by zero causes a ZeroDivisionError.
Example: Division
total_pizza_slices = 12
people = 4
# Divide the slices equally.
slices_per_person = total_pizza_slices / people
print(slices_per_person)
Output Explanation: Python divides 12 by 4. Regular division returns 3.0 rather than 3 because the slash operator produces a floating-point value. Each person receives three slices in this example.
5.8 Floor Division
Floor division uses two forward slashes. It divides one number by another and rounds the result down to the nearest whole value. This is useful when only complete groups or complete items can be counted. Floor division behaves differently with negative numbers because it always rounds toward the lower value.
Example: Floor Division
cookies = 17
children = 5
# Count complete cookies per child.
cookies_each = cookies // children
print(cookies_each)
Output Explanation: Seventeen divided by five is 3.4, but floor division keeps only the lower whole result, 3. This means each child can receive three complete cookies, with some cookies left over.
5.9 Modulus
The modulus operator uses the percent sign and returns the remainder after division. It is useful for checking even or odd numbers, repeating patterns, time calculations, and whether values divide evenly. For example, a number is even when dividing it by 2 leaves a remainder of zero.
Example: Modulus
number = 17
# Find the remainder after division by 2.
remainder = number % 2
print(remainder)
Output Explanation: Seventeen cannot be divided evenly by two. After making eight complete groups of two, one remains. Therefore, the modulus operator returns 1, showing that 17 is an odd number.
5.10 Exponentiation
Exponentiation uses two asterisks and raises one number to the power of another. For example, 2 raised to the power of 3 means 2 multiplied by itself three times. This operator is useful for squares, cubes, scientific calculations, compound growth, geometry, and many other mathematical tasks.
Example: Exponentiation
base = 2
power = 3
# Raise 2 to the power of 3.
result = base ** power
print(result)
Output Explanation: Python calculates 2 × 2 × 2 because the exponent is 3. The answer is 8. The first operand is the base, and the second operand tells Python how many times to use the base as a factor.
5.11 Assignment Operators
Assignment operators store values in variables. The basic assignment operator is the equals sign. It does not mean mathematical equality in this context; instead, it tells Python to evaluate the value on the right and store it under the variable name on the left. Assignment is used throughout almost every Python program.
Example: Assignment Operators
# Assign a value to a variable.
student_score = 85
# Assign the value of one variable to another.
saved_score = student_score
print(saved_score)
Output Explanation: The first assignment stores 85 in student_score. The second assignment reads that value and stores it in saved_score. Printing saved_score displays 85. The equals sign performs storage, not a comparison.
5.12 Augmented Assignment Operators
Augmented assignment operators combine an operation with assignment. Examples include +=, -=, *=, and /=. They provide a shorter way to update a variable using its current value. For example, score += 5 means the same as score = score + 5. These operators make repeated updates easier to read.
Example: Augmented Assignment Operators
score = 10
# Add 5 to the current score.
score += 5
# Multiply the updated score by 2.
score *= 2
print(score)
Output Explanation: First, score += 5 changes 10 to 15. Next, score *= 2 multiplies the current value, 15, by 2. The final value stored in score is 30, which print() displays.
5.13 Comparison Operators
Comparison operators compare two values and return either True or False. They include equal to, not equal to, greater than, less than, greater than or equal to, and less than or equal to. Comparisons are essential for decisions because they allow a program to test ages, prices, passwords, scores, and other conditions.
Example: Comparison Operators
age = 16
print(age >= 13)
print(age < 18)
print(age == 16)
Output Explanation: All three comparisons are correct. Sixteen is at least thirteen, less than eighteen, and exactly equal to sixteen. Because each statement is true, Python prints True for every comparison.
5.14 Equality and Inequality
The equality operator uses two equals signs and checks whether two values are equal. The inequality operator uses an exclamation mark followed by an equals sign and checks whether values are different. Beginners must remember that one equals sign assigns a value, while two equals signs compare values and return a Boolean result.
Example: Equality and Inequality
saved_password = "python123"
entered_password = "python123"
print(saved_password == entered_password)
print(saved_password != entered_password)
Output Explanation: The two strings contain exactly the same characters, so the equality comparison is True. Because they are not different, the inequality comparison is False. String comparisons are case-sensitive.
5.15 Greater Than and Less Than
Greater-than and less-than operators compare the size or order of values. The greater-than sign checks whether the left value is larger, while the less-than sign checks whether it is smaller. Versions with an equals sign also accept equal values. These operators are often used for age limits, scores, prices, and ranges.
Example: Greater Than and Less Than
temperature = 24
print(temperature > 20)
print(temperature < 30)
print(temperature >= 24)
print(temperature <= 23)
Output
True
True
True
False
Output Explanation: Twenty-four is greater than twenty and less than thirty. It is also equal to twenty-four, so the greater-than-or-equal comparison is True. It is not less than or equal to twenty-three, so the final result is False.
5.16 Logical Operators
Logical operators combine or reverse Boolean conditions. Python provides and, or, and not. They are useful when a decision depends on more than one test. For example, a person may need the correct age and a valid ticket. Logical operators return Boolean results and are commonly used inside if statements.
Example: Logical Operators
age = 15
has_ticket = True
can_enter = age >= 13 and has_ticket
print(can_enter)
Output Explanation: The first condition checks that the age is at least thirteen. The second condition checks that has_ticket is True. Because both conditions are true and they are joined with and, can_enter becomes True.
5.17 and
The and operator returns True only when both conditions are true. If either condition is false, the complete result is False. It is helpful when several requirements must all be satisfied, such as having enough money and an item being available, or entering the correct username and the correct password.
Example: and
money = 25
item_price = 20
item_in_stock = True
can_buy = money >= item_price and item_in_stock
print(can_buy)
Output Explanation: The customer has at least twenty dollars, and the item is in stock. Since both conditions are true, the and operator returns True. If either condition changed to false, can_buy would become False.
5.18 or
The or operator returns True when at least one condition is true. It returns False only when all connected conditions are false. This operator is useful when there are several acceptable choices, such as paying with cash or a card, entering with a ticket or membership, or selecting one of multiple valid options.
Example: or
has_ticket = False
has_membership = True
can_enter = has_ticket or has_membership
print(can_enter)
Output Explanation: The person does not have a ticket, but does have a membership. Because the or operator needs only one true condition, the complete expression returns True and the person can enter.
5.19 not
The not operator reverses a Boolean value. True becomes False, and False becomes True. It is useful when a program needs to check that something is not happening, such as an account not being blocked or an item not being sold out. It can make negative conditions easier to express.
Example: not
is_store_closed = False
# Reverse the value.
is_store_open = not is_store_closed
print(is_store_open)
Output Explanation: is_store_closed is False. The not operator reverses False to True, so is_store_open becomes True. This shows how not can create the opposite meaning of a Boolean condition.
5.20 Identity Operators
Identity operators check whether two variables refer to the exact same object in memory. Python provides is and is not. Identity is different from equality: two objects may contain equal values but still be separate objects. Identity checks are especially useful with None and when understanding references to mutable objects.
Example: Identity Operators
first_list = [1, 2, 3]
second_list = first_list
print(first_list is second_list)
Output Explanation: second_list receives a reference to the same list object as first_list. Therefore, both variable names point to one object in memory, and the is comparison returns True.
5.21 is and is not
The is operator returns True when two references point to the same object. The is not operator returns True when they point to different objects. Beginners should normally use == to compare values and use is mainly for identity checks such as value is None. Using is for ordinary number or string equality can be unreliable.
Example: is and is not
value = None
print(value is None)
print(value is not None)
Output Explanation: The variable value refers to Python's single None object. Therefore, value is None returns True. The opposite check, value is not None, returns False. This is the recommended way to test for None.
5.22 Membership Operators
Membership operators check whether a value exists inside a collection or sequence. Python provides in and not in. They work with strings, lists, tuples, sets, dictionaries, and other iterable objects. Membership checks are useful for searching names, validating choices, checking letters, and confirming whether a key exists in a dictionary.
Example: Membership Operators
fruits = ["apple", "banana", "orange"]
print("banana" in fruits)
print("grape" in fruits)
Output Explanation: Banana is one of the items in the fruits list, so the first membership test returns True. Grape is not present in the list, so the second test returns False.
5.23 in and not in
The in operator returns True when a value is found inside another object. The not in operator returns True when the value is absent. With dictionaries, these operators check keys by default rather than values. They are simple and readable tools for validation, searches, filters, and conditional decisions.
Example: in and not in
allowed_colors = ("red", "green", "blue")
chosen_color = "yellow"
print(chosen_color in allowed_colors)
print(chosen_color not in allowed_colors)
Output Explanation: Yellow is not included in the tuple of allowed colors. Therefore, the in test is False, while the not in test is True. Both results describe the same membership situation from opposite directions.
5.24 Bitwise Operators
Bitwise operators work with the binary digits of integers. They compare, combine, reverse, or shift individual bits. Python includes bitwise AND, OR, XOR, NOT, left shift, and right shift. These operators are less common for beginners but are useful in permissions, masks, low-level data work, networking, graphics, and performance-sensitive tasks.
Example: Bitwise Operators
a = 6 # Binary: 110
b = 3 # Binary: 011
print(a & b)
print(a | b)
Output Explanation: Bitwise AND keeps positions where both numbers have a 1, producing binary 010, which equals 2. Bitwise OR keeps positions where either number has a 1, producing binary 111, which equals 7.
5.25 Bitwise AND
Bitwise AND uses one ampersand. It compares corresponding binary bits and produces 1 only when both bits are 1. Otherwise, it produces 0. This operator is often used with bit masks to test permissions or settings. It is different from the logical and operator, which works with truth conditions.
Example: Bitwise AND
first = 6 # 110 in binary
second = 3 # 011 in binary
result = first & second
print(result)
Output Explanation: Comparing 110 and 011 bit by bit gives 010. Only the middle position contains 1 in both numbers. Binary 010 equals decimal 2, so Python prints 2.
5.26 Bitwise OR
Bitwise OR uses one vertical bar. It compares corresponding binary bits and produces 1 when either bit is 1. It produces 0 only when both bits are 0. This operator can combine permission flags and binary settings. It must not be confused with the logical or keyword used with Boolean conditions.
Example: Bitwise OR
first = 6 # 110
second = 3 # 011
result = first | second
print(result)
Output Explanation: Bitwise OR compares 110 with 011. Every bit position contains at least one 1, so the result is 111. Binary 111 is decimal 7, which is displayed.
5.27 Bitwise XOR
Bitwise XOR uses the caret symbol. It produces 1 when the corresponding bits are different and 0 when they are the same. XOR means exclusive OR. It is useful for toggling bits, detecting differences, simple checks, and some algorithms. Applying XOR with the same value twice restores the original value.
Example: Bitwise XOR
first = 6 # 110
second = 3 # 011
result = first ^ second
print(result)
Output Explanation: Comparing 110 and 011 with XOR gives 101. The first and last bit positions are different, while the middle bits are the same. Binary 101 equals decimal 5.
5.28 Bitwise NOT
Bitwise NOT uses the tilde symbol and reverses all bits of an integer. Python represents signed integers in a way that makes the result equal to negative n minus one. Therefore, ~5 becomes -6. This may surprise beginners, so it is important to remember the rule: ~n equals -(n + 1).
Example: Bitwise NOT
number = 5
result = ~number
print(result)
Output Explanation: Python applies the bitwise NOT rule to 5. The result is -(5 + 1), which is -6. This is related to how negative binary integers are represented, not ordinary Boolean negation.
5.29 Left Shift
The left-shift operator uses two less-than signs. It moves the binary bits of an integer to the left by a chosen number of positions. For non-negative integers, shifting left once is similar to multiplying by two. Shifting left by n positions is similar to multiplying by 2 raised to n.
Example: Left Shift
number = 5
# Shift the bits left by one position.
result = number << 1
print(result)
Output Explanation: Five is 101 in binary. Shifting left once produces 1010, which equals decimal 10. For this positive number, the operation has the same effect as multiplying 5 by 2.
5.30 Right Shift
The right-shift operator uses two greater-than signs. It moves binary bits to the right by a chosen number of positions. For non-negative integers, shifting right once is similar to floor-dividing by two. Bits moved beyond the right side are discarded, so information may be lost during the operation.
Example: Right Shift
number = 10
# Shift the bits right by one position.
result = number >> 1
print(result)
Output Explanation: Ten is 1010 in binary. Shifting right once produces 101, which equals decimal 5. For this positive integer, the operation acts like floor division by 2.
5.31 Operator Precedence
Operator precedence determines which operation Python performs first when an expression contains several operators. Exponentiation happens before multiplication and division, which happen before addition and subtraction. Parentheses have the highest practical priority and make the intended order clear. Beginners should use parentheses whenever an expression could be confusing.
Example: Operator Precedence
result_without_parentheses = 2 + 3 * 4
result_with_parentheses = (2 + 3) * 4
print(result_without_parentheses)
print(result_with_parentheses)
Output Explanation: Without parentheses, Python multiplies 3 by 4 first and then adds 2, producing 14. With parentheses, Python adds 2 and 3 first, then multiplies 5 by 4, producing 20.
5.32 Associativity
Associativity decides the direction in which operators of the same precedence are evaluated. Most arithmetic operators are evaluated from left to right. Exponentiation is an important exception because it is evaluated from right to left. Understanding associativity helps explain why expressions with repeated operators may produce results that beginners do not initially expect.
Example: Associativity
left_to_right = 20 / 5 * 2
right_associative_power = 2 ** 3 ** 2
print(left_to_right)
print(right_associative_power)
Output Explanation: Division and multiplication have equal precedence, so Python evaluates 20 / 5 first, then multiplies by 2. Exponentiation works right to left, so Python calculates 3 ** 2 first and then 2 ** 9.
5.33 Chained Comparisons
Python allows several comparisons to be joined in one readable expression. For example, 1 < age < 18 checks that age is greater than 1 and less than 18. Python treats this like two comparisons joined with and, while evaluating the middle value only once. Chained comparisons are useful for ranges.
Example: Chained Comparisons
age = 15
is_teen_range = 13 <= age <= 19
print(is_teen_range)
Output Explanation: Python checks that 15 is at least 13 and no more than 19. Both comparisons are true, so the chained comparison returns True. This is shorter and clearer than writing two separate comparisons with and.
5.34 The Walrus Operator
The walrus operator uses colon followed by an equals sign. It assigns a value to a variable while that value is being used inside a larger expression. This can reduce repeated calculations, especially in loops and conditions. Beginners should use it carefully because ordinary assignment is often easier to read in simple programs.
Example: The Walrus Operator
# Assign the length while comparing it.
message = "Python"
if (length := len(message)) > 5:
print(length)
Output Explanation: len(message) returns 6. The walrus operator stores 6 in length while the if condition checks whether it is greater than 5. The condition is true, so print() displays 6.
5.35 Practical Operator Examples
Operators become easier to understand when they are combined in practical tasks. A program may calculate a subtotal, apply a discount, compare the final price with a budget, and check stock availability. This section shows how arithmetic, comparison, and logical operators can work together to solve a small real-world problem.
Example: Practical Operator Examples
price = 40
quantity = 2
discount = 10
budget = 75
in_stock = True
subtotal = price * quantity
final_total = subtotal - discount
can_buy = final_total <= budget and in_stock
print(final_total)
print(can_buy)
Output Explanation: Multiplication calculates an 80-dollar subtotal. Subtraction applies the 10-dollar discount, leaving 70 dollars. The logical expression confirms that 70 is within the budget and the item is in stock, so it returns True.
5.36 Chapter Practice Exercises
Practice exercises help beginners remember how every operator works. Start with small expressions, predict the result before running the code, and then compare your prediction with Python's output. Practice arithmetic, assignments, comparisons, logical conditions, membership tests, and precedence. Making small mistakes is useful because correcting them strengthens understanding.
Example: Chapter Practice Exercises
# Exercise answers.
number = 12
print(number + 8)
print(number % 5)
print(10 < number < 20)
print(number in [5, 12, 18])
Output Explanation: The first result adds 8 to 12. The modulus result is 2 because 12 divided by 5 leaves 2. Twelve is between 10 and 20, and it is also present in the list, so both Boolean results are True.
5.37 Chapter Mini Project
This mini project combines several Chapter 5 operators in a simple shopping calculator. The program uses multiplication to calculate a subtotal, subtraction to apply a discount, addition to include tax, and comparisons to check whether the customer has enough money. Building a complete small program helps beginners connect individual operators to a useful task.
Example: Chapter Mini Project
# Simple shopping calculator.
item_price = 15
quantity = 3
discount = 5
tax = 4
customer_money = 50
subtotal = item_price * quantity
after_discount = subtotal - discount
final_total = after_discount + tax
enough_money = customer_money >= final_total
change = customer_money - final_total
print("Subtotal:", subtotal)
print("Final total:", final_total)
print("Enough money:", enough_money)
print("Change:", change)
Output
Subtotal: 45
Final total: 44
Enough money: True
Change: 6
Output Explanation: Three items cost 45 dollars. The program subtracts a 5-dollar discount and adds 4 dollars of tax, producing a final total of 44 dollars. Since the customer has 50 dollars, enough_money is True, and the remaining change is 6 dollars.