Python operators are symbols that perform operations on Python objects. There are several different types of Python operators, including arithmetic operators, relational operators, logical operators, bitwise operators, membership operators, and identity operators.
Arithmetic operators are used to perform basic mathematical operations, such as addition, subtraction, multiplication, division, and exponentiation. For example:
Python
# Addition
print(5 + 2) # Outputs 7
# Subtraction
print(5 - 2) # Outputs 3
# Multiplication
print(5 * 2) # Outputs 10
# Division
print(5 / 2) # Outputs 2.5
# Exponentiation
print(5 ** 2) # Outputs 25
Relational operators are used to compare two Python objects and return a Boolean value (True or False) indicating the relationship between the two objects. For example:
Python
# Greater than
print(5 > 2) # Outputs True
# Less than
print(5 < 2) # Outputs False
# Greater than or equal to
print(5 >= 2) # Outputs True
# Less than or equal to
print(5 <= 2) # Outputs False
# Equal to
print(5 == 2) # Outputs False
# Not equal to
print(5 != 2) # Outputs True
Logical operators are used to combine two Boolean values and return a Boolean value (True or False) indicating the relationship between the two values. For example:
Python
# And operator
print(5 > 2 and 10 > 5) # Outputs True
# Or operator
print(5 > 2 or 10 < 5) # Outputs True
# Not operator
print(not 5 > 2) # Outputs False
Bitwise operators are used to perform bit-level operations on Python integers. For example:
Python
# Bitwise AND
print(5 & 2) # Outputs 0
# Bitwise OR
print(5 | 2) # Outputs 7
# Bitwise XOR
print(5 ^ 2) # Outputs 7
# Bitwise NOT
print(~5) # Outputs -6
Membership operators are used to check if an object is contained in a sequence or collection. For example:
Python
# Check if a string is contained in a list
my_list = ["Hello", "World!"]
print("Hello" in my_list) # Outputs True
# Check if a number is contained in a set
my_set = {1, 2, 3}
print(2 in my_set) # Outputs True
Identity operators are used to check if two objects are the same object. For example:
Python
# Check if two variables refer to the same object
my_variable1 = 5
my_variable2 = 5
print(my_variable1 is my_variable2) # Outputs True
# Check if two strings are the same object
my_string1 = "Hello, World!"
my_string2 = "Hello, World!"
print(my_string1 is my_string2) # Outputs False
Python operators are a powerful tool that can be used to perform a wide variety of tasks. By understanding how to use operators, you can write more efficient and readable Python code.
Here are some additional tips for using operators in Python: