Python Operators
Operators in Python programming are special symbols or keywords that perform operations on variables and values. They are fundamental building blocks that allow developers to manipulate data, perform calculations, make comparisons, and control program flow. Python operators take one or more operands (values or variables) and produce a result based on the specific operation being performed. There are seven different operators in Python:
- Arithmetic Operators: Used to perform mathematical calculations like addition, subtraction, multiplication, and division.
- Assignment Operators: Used to assign values to variables and update them with operations.
- Comparison Operators: Used to compare two values and return a Boolean result (True or False).
- Logical Operators: Used to combine multiple conditions and return a Boolean outcome.
- Bitwise Operators: Used to perform operations at the binary (bit) level on integers.
- Membership Operators: Used to test whether a value exists within a sequence such as a list or string.
- Identity Operators: Used to check whether two variables refer to the exact same object in memory.
Arithmetic Operators
Arithmetic operators perform mathematical operations on numeric values such as addition, subtraction, multiplication, and division. These operators are essential for mathematical calculations, data processing, and numerical computations in Python programs.
These are the arithmetic operators available in Python:
| Operator | Name | Description | Example |
|---|---|---|---|
+ |
Addition | Adds two operands | x + y |
- |
Subtraction | Subtracts right operand from left operand | x - y |
* |
Multiplication | Multiplies two operands | x * y |
/ |
Division | Divides left operand by right operand | x / y |
% |
Modulus | Returns remainder of division | x % y |
** |
Exponentiation | Raises left operand to power of right operand | x ** y |
// |
Floor Division | Returns floor of division result | x // y |
Example of Arithmetic Operator in Python
# Shopping cart total calculationitem_price = 25.99quantity = 3tax_rate = 0.08# Calculate subtotal using multiplicationsubtotal = item_price * quantity# Calculate tax using multiplicationtax_amount = subtotal * tax_rate# Calculate total using additiontotal = subtotal + tax_amount# Calculate change from $100 using subtractionpayment = 100.00change = payment - total# Display resultsprint(f"Subtotal: ${subtotal:.2f}")print(f"Tax: ${tax_amount:.2f}")print(f"Total: ${total:.2f}")print(f"Change: ${change:.2f}")
The output of this code is:
Subtotal: $77.97Tax: $6.24Total: $84.21Change: $15.79
This example demonstrates arithmetic operators in a real-world shopping scenario where multiplication calculates subtotal and tax, addition finds the final total, and subtraction determines change.
Assignment Operators
Assignment operators are used to assign values to variables and can simultaneously perform arithmetic operations during the assignment process. These operators provide a shorthand way to update variable values by combining an arithmetic operation with assignment.
These are the assignment operators available in Python:
| Operator | Name | Description | Example | Equivalent |
|---|---|---|---|---|
= |
Assignment | Assigns value to variable | x = 5 |
x = 5 |
+= |
Addition Assignment | Adds and assigns | x += 3 |
x = x + 3 |
-= |
Subtraction Assignment | Subtracts and assigns | x -= 3 |
x = x - 3 |
*= |
Multiplication Assignment | Multiplies and assigns | x *= 3 |
x = x * 3 |
/= |
Division Assignment | Divides and assigns | x /= 3 |
x = x / 3 |
%= |
Modulus Assignment | Applies modulus and assigns | x %= 3 |
x = x % 3 |
**= |
Exponent Assignment | Raises to power and assigns | x **= 3 |
x = x ** 3 |
//= |
Floor Division Assignment | Floor divides and assigns | x //= 3 |
x = x // 3 |
Example of Python’s Assignment Operator
# Initial account balanceaccount_balance = 1000.00# Deposit money using addition assignmentdeposit_amount = 250.00account_balance += deposit_amountprint(f"After deposit: ${account_balance:.2f}")# Withdraw money using subtraction assignmentwithdrawal_amount = 75.00account_balance -= withdrawal_amountprint(f"After withdrawal: ${account_balance:.2f}")# Apply monthly interest using multiplication assignmentmonthly_interest_rate = 1.005 # 0.5% interestaccount_balance *= monthly_interest_rateprint(f"After interest: ${account_balance:.2f}")# Calculate service fee using division assignmentservice_fee_rate = 0.02 # 2% service feefee_amount = account_balancefee_amount *= service_fee_rateaccount_balance -= fee_amountprint(f"Final balance: ${account_balance:.2f}")
The output of this code is:
After deposit: $1250.00After withdrawal: $1175.00After interest: $1180.88Final balance: $1157.26
This example shows how assignment operators streamline financial calculations by combining operations with assignments in a bank account management system.
Comparison Operators
Comparison operators are used to compare two values and return a Boolean result (True or False). These operators are fundamental for decision-making in programs, allowing developers to create conditional logic, validate data, and control program flow. They work with numbers, strings, and other comparable data types, making them essential for sorting, filtering, and validation operations.
These are the comparison operators available in Python:
| Operator | Name | Description | Example |
|---|---|---|---|
== |
Equal | Returns True if operands are equal | x == y |
!= |
Not Equal | Returns True if operands are not equal | x != y |
> |
Greater Than | Returns True if left operand is greater | x > y |
< |
Less Than | Returns True if left operand is smaller | x < y |
>= |
Greater Than or Equal | Returns True if left operand is greater or equal | x >= y |
<= |
Less Than or Equal | Returns True if left operand is less or equal | x <= y |
Example of Comparison Operators in Python
# Student test scoresstudent_score = 87passing_score = 60honor_roll_score = 90perfect_score = 100# Check if student passed using greater than or equalpassed = student_score >= passing_scoreprint(f"Student passed: {passed}")# Check if student made honor roll using greater than or equalhonor_roll = student_score >= honor_roll_scoreprint(f"Honor roll: {honor_roll}")# Check if student got perfect score using equalperfect = student_score == perfect_scoreprint(f"Perfect score: {perfect}")# Check if student needs improvement using less thanneeds_improvement = student_score < passing_scoreprint(f"Needs improvement: {needs_improvement}")# Compare with class averageclass_average = 82above_average = student_score > class_averageprint(f"Above class average: {above_average}")
The output of this code is:
Student passed: TrueHonor roll: FalsePerfect score: FalseNeeds improvement: FalseAbove class average: True
This example demonstrates comparison operators in an educational context where different score thresholds determine student performance levels.
Logical Operators
Logical operators perform logical operations on Boolean values and expressions, returning Boolean results based on the logical relationship between operands. These operators are crucial for creating complex conditional statements, combining multiple conditions, and implementing decision-making logic in programs.
These are the logical operators available in Python:
| Operator | Name | Description | Example |
|---|---|---|---|
and |
Logical AND | Returns True if both operands are True | x and y |
or |
Logical OR | Returns True if at least one operand is True | x or y |
not |
Logical NOT | Returns opposite Boolean value | not x |
Example of Python’s Logical Operators
# User credentials and permissionsuser_authenticated = Trueuser_role = "admin"account_active = Truemaintenance_mode = False# Check if user can access admin panel using 'and'admin_access = user_authenticated and user_role == "admin" and account_activeprint(f"Admin access granted: {admin_access}")# Check if user can access system using 'or'basic_access = user_authenticated and account_active or user_role == "guest"print(f"Basic access granted: {basic_access}")# Check if system is available using 'not'system_available = not maintenance_mode and account_activeprint(f"System available: {system_available}")# Complex access control logicfull_access = (user_authenticated and account_active) and (user_role == "admin" or user_role == "moderator") and not maintenance_modeprint(f"Full access granted: {full_access}")
The output of this code is:
Admin access granted: TrueBasic access granted: TrueSystem available: TrueFull access granted: True
This example shows logical operators in a security system where multiple conditions must be evaluated to determine user access permissions.
Identity Operators
Identity operators compare the memory location of two objects to determine if they refer to the same object in memory, rather than comparing their values. These operators are particularly useful for checking object references, validating None values, and understanding Python’s object model. They help distinguish between objects that have the same value versus objects that are actually the same instance.
These are the identity operators available in Python:
| Operator | Name | Description | Example |
|---|---|---|---|
is |
Identity | Returns True if operands are the same object | x is y |
is not |
Not Identity | Returns True if operands are not the same object | x is not y |
Example of Identity Operators in Python
# Creating different types of objectslist1 = [1, 2, 3]list2 = [1, 2, 3]list3 = list1# Check if lists are the same object using 'is'same_object = list1 is list3print(f"list1 is list3: {same_object}")# Check if lists are different objects using 'is'different_objects = list1 is list2print(f"list1 is list2: {different_objects}")# Check if lists are not the same object using 'is not'not_same_object = list1 is not list2print(f"list1 is not list2: {not_same_object}")# Common use case: checking for Noneuser_data = Noneno_data = user_data is Noneprint(f"No user data: {no_data}")# After loading datauser_data = {"name": "John", "age": 30}has_data = user_data is not Noneprint(f"Has user data: {has_data}")
The output of this code is:
list1 is list3: Truelist1 is list2: Falselist1 is not list2: TrueNo user data: TrueHas user data: True
This example demonstrates identity operators for checking object references and validating None values, which is common in data validation scenarios.
Membership Operators
Membership operators test whether a value is present in a sequence such as strings, lists, tuples, sets, or dictionaries. These operators are essential for data validation, content filtering, and search operations. They provide an efficient way to check for the existence of elements in collections and are commonly used in conditional statements and data processing tasks. There are two membership operators avaialble in Python: Python in operator and not in operator.
| Operator | Name | Description | Example |
|---|---|---|---|
in |
Membership | Returns True if value is found in sequence | x in sequence |
not in |
Not Membership | Returns True if value is not found in sequence | x not in sequence |
Example of Membership Operators in Python
# Content filtering for a social media platformblocked_words = ["spam", "scam", "fake", "virus"]user_message = "This is a legitimate message about our product"suspicious_message = "This is a spam message with fake offers"# Check if message contains blocked words using 'in'contains_blocked = any(word in user_message.lower() for word in blocked_words)print(f"Message contains blocked words: {contains_blocked}")# Check specific word using 'in'has_spam = "spam" in suspicious_message.lower()print(f"Message contains 'spam': {has_spam}")# Check if word is not in blocked list using 'not in'safe_word = "product"is_safe = safe_word not in blocked_wordsprint(f"'{safe_word}' is safe to use: {is_safe}")# Check user permissionsallowed_users = ["admin", "moderator", "verified_user"]current_user = "regular_user"has_permission = current_user in allowed_usersprint(f"User has permission: {has_permission}")# Check if user is not in banned listbanned_users = ["spammer123", "troll456"]is_banned = current_user in banned_usersprint(f"User is banned: {is_banned}")
The output of this code is:
Message contains blocked words: FalseMessage contains 'spam': True'product' is safe to use: TrueUser has permission: FalseUser is banned: False
This example shows membership operators in a content moderation system where text and user validation are performed using sequence membership tests.
Bitwise Operators
Bitwise operators perform operations on the binary representations of numbers at the individual bit level. These operators are used in low-level programming, system programming, and performance-critical applications where direct manipulation of bits is required. They are commonly used for flag management, permissions systems, cryptography, and embedded programming where efficient memory usage and fast operations are essential.
These are the bitwise operators available in Python:
| Operator | Name | Description | Example |
|---|---|---|---|
& |
Bitwise AND | Returns 1 if both bits are 1 | x & y |
| |
Bitwise OR | Returns 1 if at least one bit is 1 | x | y |
^ |
Bitwise XOR | Returns 1 if bits are different | x ^ y |
~ |
Bitwise NOT | Returns complement of bits | ~x |
<< |
Left Shift | Shifts bits to the left | x << 2 |
>> |
Right Shift | Shifts bits to the right | x >> 2 |
Example of Bitwise Operators in Python
# Permission flags for a file systemREAD = 4 # 100 in binaryWRITE = 2 # 010 in binaryEXECUTE = 1 # 001 in binary# User permissions using bitwise OR to combine flagsuser_permissions = READ | WRITE # 110 in binary (6 in decimal)print(f"User permissions: {user_permissions}")# Check if user has read permission using bitwise ANDhas_read = bool(user_permissions & READ)print(f"Has read permission: {has_read}")# Check if user has write permission using bitwise ANDhas_write = bool(user_permissions & WRITE)print(f"Has write permission: {has_write}")# Check if user has execute permission using bitwise ANDhas_execute = bool(user_permissions & EXECUTE)print(f"Has execute permission: {has_execute}")# Add execute permission using bitwise ORuser_permissions = user_permissions | EXECUTEprint(f"Updated permissions: {user_permissions}")# Remove write permission using bitwise XORuser_permissions = user_permissions ^ WRITEprint(f"After removing write: {user_permissions}")# Double a number using left shift (equivalent to multiplying by 2)number = 5doubled = number << 1print(f"{number} doubled using left shift: {doubled}")
The output of this code is:
User permissions: 6Has read permission: TrueHas write permission: TrueHas execute permission: FalseUpdated permissions: 7After removing write: 55 doubled using left shift: 10
This example demonstrates bitwise operators in a file permission system where flags are combined and checked using binary operations, which is memory-efficient for managing multiple boolean states.
Frequently Asked Questions
1. What is an operator in Python?
An operator in Python is a symbol or keyword used to perform operations on values or variables. These operations can include math, comparisons, logic checks, and more.
2. How many operators are there in Python?
Python has seven main types of operators: arithmetic, assignment, comparison, logical, bitwise, membership, and identity. Each type includes several specific operators used for different tasks.
3. What is the difference between = and == operators?
The = operator assigns a value to a variable, while == compares two values for equality. Use = for assignment and == for comparison.
All contributors
- Anonymous contributor
- MamtaWardhani
Sriparno08
DaniTellini- fajardomike
fariamg- StevenSwiniarski
christian.dinh
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours