Python Operators

Operators in Python are special symbols that perform computations on variables and values. They allow us to carry out operations like arithmetic, comparisons, and logical assessments in our code. Understanding how these operators work is crucial to manipulating data effectively in Python.

Types of Python Operators

Python provides a variety of operators, which can be categorized as follows:

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical operations such as addition, subtraction, multiplication, and division.

Code Example


# Arithmetic Operators Example
a = 15
b = 4

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
print("Floor Division:", a // b)
            

Output

Addition: 19 Subtraction: 11 Multiplication: 60 Division: 3.75 Modulus: 3 Exponentiation: 50625 Floor Division: 3

2. Comparison Operators

Comparison operators compare two values and return a boolean result: either True or False.

Code Example


# Comparison Operators Example
x = 10
y = 20

print("x == y:", x == y)
print("x != y:", x != y)
print("x > y:", x > y)
print("x < y:", x < y)
print("x >= y:", x >= y)
print("x <= y:", x <= y)
            

Output

x == y: False x != y: True x > y: False x < y: True x >= y: False x <= y: True

3. Logical Operators

Logical operators are used to combine conditional statements.

Code Example


# Logical Operators Example
a = True
b = False

print("a and b:", a and b)
print("a or b:", a or b)
print("not a:", not a)
            

Output

a and b: False a or b: True not a: False

4. Assignment Operators

Assignment operators are used to assign values to variables.

5. Bitwise Operators

Bitwise operators are used to compare (binary) numbers.

6. Membership Operators

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

7. Identity Operators

Identity operators are used to compare the memory locations of two objects.

Python operators are fundamental tools that allow you to perform various computations and logical operations. Understanding how to use these operators effectively is crucial for writing efficient Python code.