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:
- Arithmetic Operators
- Comparison (Relational) Operators
- Logical Operators
- Assignment Operators
- Bitwise Operators
- Membership Operators
- Identity Operators
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
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
3. Logical Operators
Logical operators are used to combine conditional statements.
and
: Returns True if both statements are trueor
: Returns True if one of the statements is truenot
: Reverses the result, returns False if the result is true
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
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.
in
: Returns True if a sequence with the specified value is present in the objectnot in
: Returns True if a sequence with the specified value is not present in the object
7. Identity Operators
Identity operators are used to compare the memory locations of two objects.
is
: Returns True if both variables are the same objectis not
: Returns True if both variables are not the same object
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.