Python is a high-level programming language that supports a wide range of operators. Operators are special symbols or keywords that perform specific operations on one or more operands. In Python, operators are used to manipulate data and perform various operations such as arithmetic, comparison, logical, bitwise, and assignment.
Python operators can be classified into several categories based on their functionality. Here are some of the most commonly used operators in Python:
Arithmetic operators are used to perform mathematical operations such as addition, subtraction, multiplication, division, modulus, and exponentiation. Here are some examples:
a = 10
b = 5
# Addition
print(a + b) # Output: 15
# Subtraction
print(a - b) # Output: 5
# Multiplication
print(a * b) # Output: 50
# Division
print(a / b) # Output: 2.0
# Modulus
print(a % b) # Output: 0
# Exponentiation
print(a ** b) # Output: 100000
Comparison operators are used to compare two values and return a Boolean value (True or False) based on the comparison. Here are some examples:
a = 10
b = 5
# Greater than
print(a > b) # Output: True
# Less than
print(a < b) # Output: False
# Equal to
print(a == b) # Output: False
# Not equal to
print(a != b) # Output: True
# Greater than or equal to
print(a >= b) # Output: True
# Less than or equal to
print(a <= b) # Output: False
Logical operators are used to combine two or more Boolean expressions and return a Boolean value based on the result of the combination. Here are some examples:
a = True
b = False
# Logical AND
print(a and b) # Output: False
# Logical OR
print(a or b) # Output: True
# Logical NOT
print(not a) # Output: False
Bitwise operators are used to perform bitwise operations on binary numbers. Here are some examples:
a = 60
b = 13
# Bitwise AND
print(a & b) # Output: 12
# Bitwise OR
print(a | b) # Output: 61
# Bitwise XOR
print(a ^ b) # Output: 49
# Bitwise NOT
print(~a) # Output: -61
# Bitwise left shift
print(a << 2) # Output: 240
# Bitwise right shift
print(a >> 2) # Output: 15
Assignment operators are used to assign values to variables. Here are some examples:
a = 10
b = 5
# Simple assignment
c = a + b
print(c) # Output: 15
# Add and assign
a += b
print(a) # Output: 15
# Subtract and assign
a -= b
print(a) # Output: 10
# Multiply and assign
a *= b
print(a) # Output: 50
# Divide and assign
a /= b
print(a) # Output: 10.0
# Modulus and assign
a %= b
print(a) # Output: 0.0
# Exponentiation and assign
a **= b
print(a) # Output: 100000000000
Python operators are an essential part of the language and are used extensively in programming. Understanding the different types of operators and their functionality is crucial for writing efficient and effective code.