Skip to main content

Python Operators

Introduction

Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand. For example, in the expression 2 + 3, + is the operator and 2 and 3 are the operands.

Python provides a variety of operators grouped into several categories. Understanding these operators is crucial for writing efficient Python code and implementing logic in your programs.

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc.

OperatorDescriptionExample
+Additionx + y
-Subtractionx - y
*Multiplicationx * y
/Divisionx / y
%Modulus (remainder)x % y
**Exponentiationx ** y
//Floor divisionx // y

Examples

python
a = 10
b = 3

# Addition
print(f"a + b = {a + b}") # 13

# Subtraction
print(f"a - b = {a - b}") # 7

# Multiplication
print(f"a * b = {a * b}") # 30

# Division
print(f"a / b = {a / b}") # 3.3333333333333335

# Modulus
print(f"a % b = {a % b}") # 1

# Exponentiation
print(f"a ** b = {a ** b}") # 1000

# Floor Division
print(f"a // b = {a // b}") # 3

Assignment Operators

Assignment operators are used to assign values to variables.

OperatorDescriptionExampleEquivalent to
=Assign valuex = 5x = 5
+=Add and assignx += 5x = x + 5
-=Subtract and assignx -= 5x = x - 5
*=Multiply and assignx *= 5x = x * 5
/=Divide and assignx /= 5x = x / 5
%=Modulus and assignx %= 5x = x % 5
**=Exponentiate and assignx **= 5x = x ** 5
//=Floor divide and assignx //= 5x = x // 5

Examples

python
x = 10

# Add and assign
x += 5
print(f"After x += 5: {x}") # 15

# Reset x
x = 10

# Subtract and assign
x -= 3
print(f"After x -= 3: {x}") # 7

# Reset x
x = 10

# Multiply and assign
x *= 2
print(f"After x *= 2: {x}") # 20

Comparison Operators

Comparison operators are used to compare values. They return either True or False according to the condition.

OperatorDescriptionExample
==Equal tox == y
!=Not equal tox != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equal tox >= y
<=Less than or equal tox <= y

Examples

python
a = 10
b = 5
c = 10

print(f"a == b: {a == b}") # False
print(f"a != b: {a != b}") # True
print(f"a > b: {a > b}") # True
print(f"a < b: {a < b}") # False
print(f"a >= c: {a >= c}") # True
print(f"a <= c: {a <= c}") # True

Logical Operators

Logical operators are used to combine conditional statements.

OperatorDescriptionExample
andReturns True if both statements are truex < 5 and x < 10
orReturns True if one of the statements is truex < 5 or x < 4
notReverse the result, returns False if the result is truenot(x < 5 and x < 10)

Examples

python
x = 5

print(f"x > 3 and x < 10: {x > 3 and x < 10}") # True
print(f"x > 8 or x < 4: {x > 8 or x < 4}") # False
print(f"not(x > 8): {not(x > 8)}") # True

Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object with the same memory location.

OperatorDescriptionExample
isReturns True if both variables reference the same objectx is y
is notReturns True if both variables do not reference the same objectx is not y

Examples

python
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(f"a is b: {a is b}") # False, they are different objects
print(f"a is c: {a is c}") # True, they reference the same object
print(f"a is not b: {a is not b}") # True

Membership Operators

Membership operators are used to test if a sequence is presented in an object.

OperatorDescriptionExample
inReturns True if a sequence with the specified value is present in the objectx in y
not inReturns True if a sequence with the specified value is not present in the objectx not in y

Examples

python
fruits = ["apple", "banana", "cherry"]

print(f"'apple' in fruits: {'apple' in fruits}") # True
print(f"'orange' in fruits: {'orange' in fruits}") # False
print(f"'orange' not in fruits: {'orange' not in fruits}") # True

Bitwise Operators

Bitwise operators are used to compare binary numbers.

OperatorDescriptionExample
&ANDx & y
|ORx | y
^XORx ^ y
~NOT~x
<<Zero fill left shiftx << n
>>Signed right shiftx >> n

Examples

python
a = 10  # binary: 1010
b = 7 # binary: 0111

# Bitwise AND
print(f"a & b: {a & b}") # 2 (binary: 0010)

# Bitwise OR
print(f"a | b: {a | b}") # 15 (binary: 1111)

# Bitwise XOR
print(f"a ^ b: {a ^ b}") # 13 (binary: 1101)

# Bitwise NOT
print(f"~a: {~a}") # -11 (binary: -1011)

# Left Shift
print(f"a << 2: {a << 2}") # 40 (binary: 101000)

# Right Shift
print(f"a >> 2: {a >> 2}") # 2 (binary: 10)

Operator Precedence

Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated before operators with lower precedence.

Here's a simplified list of Python operator precedence (from highest to lowest):

  1. ** (Exponentiation)
  2. ~, +, - (Bitwise NOT, Unary plus and minus)
  3. *, /, //, % (Multiplication, Division, Floor division, Modulus)
  4. +, - (Addition, Subtraction)
  5. <<, >> (Bitwise shift operators)
  6. & (Bitwise AND)
  7. ^ (Bitwise XOR)
  8. | (Bitwise OR)
  9. ==, !=, >, >=, <, <=, is, is not, in, not in (Comparisons, Identity, Membership)
  10. not (Logical NOT)
  11. and (Logical AND)
  12. or (Logical OR)

Example

python
result = 10 + 3 * 2 ** 2
print(f"10 + 3 * 2 ** 2 = {result}") # 22

# Explanation:
# 1. 2 ** 2 = 4 (Exponentiation has highest precedence)
# 2. 3 * 4 = 12 (Multiplication is next)
# 3. 10 + 12 = 22 (Addition is last)

Real-World Applications

1. Calculating Total Cost with Discount

python
def calculate_total(price, quantity, discount_rate=0):
"""Calculate the total cost after applying a discount."""
subtotal = price * quantity
discount = subtotal * discount_rate
total = subtotal - discount
return total

# Regular purchase
regular_purchase = calculate_total(19.99, 3)
print(f"Regular purchase total: ${regular_purchase:.2f}") # $59.97

# Purchase with 15% discount
discounted_purchase = calculate_total(19.99, 3, 0.15)
print(f"Discounted purchase total: ${discounted_purchase:.2f}") # $50.97

2. User Access Control

python
def check_user_access(user_role, is_admin, is_active):
"""Check if the user has access to the admin panel."""
has_access = (user_role == "admin" or is_admin) and is_active
return has_access

# Different user scenarios
print(f"Admin user, active: {check_user_access('admin', False, True)}") # True
print(f"Regular user with admin rights, active: {check_user_access('user', True, True)}") # True
print(f"Admin user, inactive: {check_user_access('admin', False, False)}") # False
print(f"Regular user, active: {check_user_access('user', False, True)}") # False

3. List Filtering with Comprehension

python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Create a list of even numbers using operator in a comprehension
even_numbers = [num for num in numbers if num % 2 == 0]
print(f"Even numbers: {even_numbers}") # [2, 4, 6, 8, 10]

# Create a list of squares for numbers greater than 5
squares_gt5 = [num**2 for num in numbers if num > 5]
print(f"Squares of numbers > 5: {squares_gt5}") # [36, 49, 64, 81, 100]

Summary

In this module, we covered the different types of operators in Python:

  • Arithmetic Operators: Used for mathematical operations
  • Assignment Operators: Used to assign values to variables
  • Comparison Operators: Used to compare values
  • Logical Operators: Used to combine conditional statements
  • Identity Operators: Used to check if objects are the same
  • Membership Operators: Used to check if a value exists in a sequence
  • Bitwise Operators: Used to perform operations on binary representations of numbers

Understanding operators is fundamental to programming in Python. They allow you to manipulate data, control program flow, and implement complex logic in your applications.

Exercises

  1. Write a program to calculate the area and perimeter of a rectangle using arithmetic operators.
  2. Create a temperature converter that converts Celsius to Fahrenheit and vice versa using the formula F = C * 9/5 + 32.
  3. Write a program that checks if a number is even and positive using logical operators.
  4. Create a simple calculator that can perform addition, subtraction, multiplication, and division based on user input.
  5. Write a program that checks if an element exists in a list and prints an appropriate message using membership operators.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)