Skip to main content

Python Operators

In Python, operators are special symbols used to perform operations on variables and values. Python supports a wide range of operators categorized based on their functionality.

Used to perform basic mathematical operations:

OperatorDescriptionExampleResult
+Addition10 + 515
-Subtraction10 - 55
*Multiplication10 * 550
/Division10 / 52.0
//Floor Division10 // 33
%Modulus (remainder)10 % 31
**Exponentiation2 ** 38

Comparison Operators​

Used to compare two values and return a Boolean result (True or False).

OperatorDescriptionExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than5 > 3True
<Less than5 < 3False
>=Greater than or equal5 >= 5True
<=Less than or equal5 <= 3False

Logical Operators​

Used to combine conditional statements here.

OperatorDescriptionExampleResult
andTrue if both operands are trueTrue and FalseFalse
orTrue if at least one is trueTrue or FalseTrue
notReverses the resultnot TrueFalse

Assignment Operators​

Used to assign values to variables.

OperatorExampleSame as
=x = 5Assign 5 to x
+=x += 3x = x + 3
-=x -= 2x = x - 2
*=x *= 4x = x * 4
/=x /= 2x = x / 2
//=x //= 2x = x // 2
%=x %= 2x = x % 2
**=x **= 2x = x ** 2

Bitwise Operators​

Used to perform bit-level operations.

OperatorDescriptionExampleResult
&AND5 & 31
``OR`5
^XOR5 ^ 36
~NOT~5-6
<<Left Shift5 << 110
>>Right Shift5 >> 12

Membership Operators​

Used to test if a sequence contains a value.

OperatorDescriptionExampleResult
inValue exists in the sequence"a" in "apple"True
not inValue not in sequence"z" not in "apple"True

Identity Operators​

Used to compare the memory location of two objects.

OperatorDescriptionExampleResult
isReturns True if same objectx is yTrue
is notReturns True if not same objectx is not yTrue

Use Cases of Python Operators​


1. Arithmetic Operators​

πŸ“Œ Use Case: Shopping Cart Total

price = 150
quantity = 3
total = price * quantity # ➜ 450
discount = 0.10
final_amount = total - (total * discount) # ➜ 405.0

Explanation: Calculates the total bill with a discount using * and -.


2. Comparison Operators​

πŸ“Œ Use Case: Age Verification for Voting

age = 17
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible")

Explanation: Compares age using >= to determine eligibility.


3. Logical Operators​

πŸ“Œ Use Case: Login System Authentication

username = "admin"
password = "1234"

if username == "admin" and password == "1234":
print("Login successful")
else:
print("Invalid credentials")

Explanation: Combines two conditions using and.


4. Assignment Operators​

πŸ“Œ Use Case: Updating Game Score

score = 0
score += 10 # Player scored
score += 5 # Bonus
# Final score = 15

Explanation: Increments the score using +=.


5. Bitwise Operators​

πŸ“Œ Use Case: File Permission System (Read = 4, Write = 2, Execute = 1)

read = 4
write = 2
execute = 1

permission = read | write # ➜ 6 (read + write)
has_write = permission & write # ➜ 2 (True)

Explanation: Combines permissions using | and checks with &.


6. Membership Operators​

πŸ“Œ Use Case: Search Term Filtering

query = "python"
if "python" in ["java", "python", "c++"]:
print("Result found")

Explanation: Checks if a word exists in a list using in.


7. Identity Operators​

πŸ“Œ Use Case: Comparing Object Identity

x = [1, 2, 3]
y = x
z = [1, 2, 3]

print(x is y) # True
print(x is z) # False

Explanation: Uses is to check if variables point to the same object in memory.


8. Operator Precedence​

πŸ“Œ Use Case: Evaluating an Expression

result = 10 + 5 * 2  # ➜ 10 + (5 * 2) = 20

Explanation: * is evaluated before + due to higher precedence.


Summary Table​

Operator TypeExample Use Case
ArithmeticCalculating total cost
ComparisonValidating age for access
LogicalChecking login credentials
AssignmentUpdating scores or counters
BitwiseManaging file permissions (bits)
MembershipSearch and filter operations
IdentityVerifying object references
PrecedenceProper expression evaluation order

Conclusion​

Operators are the core building blocks of logic and calculation in Python. Understanding how they work is crucial to writing effective Python code.