Basic Operators and Expressions in Python
In the previous lesson on Python Variables and Data Types, we learned how to store data. Now, it is time to perform actions on that data. In Python, operators are special symbols used to carry out mathematical or logical computations. The value that the operator operates on is called the operand.
An expression is a combination of values, variables, and operators that, when evaluated, produces a single result. Understanding these building blocks is essential for writing any functional Python script.
Types of Operators in Python
Python categorizes operators based on the type of operation they perform. Let’s explore the most commonly used ones.
1. Arithmetic Operators
These are used to perform mathematical calculations like addition, subtraction, and multiplication.
- Addition (+): Adds two operands.
5 + 2 = 7 - Subtraction (-): Subtracts the right operand from the left.
5 - 2 = 3 - Multiplication (*): Multiplies two operands.
5 * 2 = 10 - Division (/): Divides the left operand by the right. Always returns a float.
10 / 2 = 5.0 - Floor Division (//): Divides and returns the largest integer less than or equal to the result.
7 // 2 = 3 - Modulus (%): Returns the remainder of the division.
7 % 2 = 1 - Exponentiation (**): Calculates the power.
5 ** 2 = 25
# Example of Arithmetic Operators
price = 100
tax_rate = 0.05
total_tax = price * tax_rate
final_price = price + total_tax
print("Total Tax:", total_tax)
print("Final Price:", final_price)
2. Comparison (Relational) Operators
Comparison operators compare two values and return a Boolean result: True or False.
- Equal to (==):
5 == 5is True. - Not equal to (!=):
5 != 3is True. - Greater than (>):
10 > 5is True. - Less than (<):
3 < 1is False. - Greater than or equal to (>=):
5 >= 5is True. - Less than or equal to (<=):
4 <= 5is True.
3. Logical Operators
Logical operators are used to combine conditional statements.
- and: Returns True if both statements are true.
(5 > 3 and 10 > 5) - or: Returns True if at least one statement is true.
(5 > 10 or 10 > 5) - not: Reverses the result.
not(5 > 3)is False.
Operator Precedence and Expressions
When multiple operators appear in a single expression, Python follows a specific order called Operator Precedence (similar to PEMDAS in mathematics).
Precedence Order (Highest to Lowest):
- Parentheses
() - Exponentiation
** - Multiplication, Division, Floor Division, Modulus
* / // % - Addition and Subtraction
+ - - Comparison Operators
== != > < - Logical
not, thenand, thenor
Expression Evaluation Diagram
Expression: 10 + 2 * 3 ** 2
Step 1: Exponentiation (3**2) -> 10 + 2 * 9
Step 2: Multiplication (2*9) -> 10 + 18
Step 3: Addition (10+18) -> 28
Final Result: 28
Real-World Use Case: E-commerce Discount Logic
In a real application, operators are used to determine if a customer is eligible for a discount based on their purchase amount and membership status.
purchase_amount = 150
is_member = True
# Logic: Discount if purchase > 100 AND they are a member
eligible_for_discount = (purchase_amount > 100) and is_member
print("Apply Discount?", eligible_for_discount)
Common Mistakes to Avoid
- Single vs. Double Equals: Using
=(assignment) instead of==(comparison) in anifstatement is a frequent beginner error. - Integer Division: Forgetting that
/always returns a float even if the result is a whole number. Use//if you need an integer. - Operator Priority: Not using parentheses in complex logical expressions, leading to unexpected
TrueorFalseresults. - String Concatenation: Trying to use
+between a string and an integer (e.g.,"Age: " + 25). You must convert the integer to a string first.
Interview Notes for Python Developers
- What is Short-Circuit Evaluation? In Python, logical operators
andandorare short-circuited. Forand, if the first expression is False, the second is not evaluated. Foror, if the first is True, the second is skipped. - Difference between `is` and `==`:
==checks for equality of values, whileischecks if both variables point to the same object in memory. - Divmod function: Mentioning the
divmod(a, b)function, which returns both the quotient and the remainder, shows advanced knowledge.
Summary
In this lesson, we covered the fundamental tools for manipulating data in Python. We learned about arithmetic operators for math, comparison operators for logic, and how operator precedence dictates the flow of expression evaluation. Mastering these operators allows you to build complex logic and data processing routines in your Python applications.
Ready to move forward? In the next topic, we will explore Control Flow: If Statements and Loops to make our programs interactive and intelligent.