Python Operators
In Python, operators are special symbols or keywords that perform operations on variables and values. Python supports various types of operators, including arithmetic operators, comparison operators, logical operators, assignment operators, and more.
1. Arithmetic Operators:
Used to perform mathematical operations.
addition = 5 + 3 # Addition
subtraction = 7 - 4 # Subtraction
multiplication = 2 * 6 # Multiplication
division = 8 / 2 # Division (returns a float)
floor_division = 8 // 3 # Floor Division (returns an integer)
remainder = 8 % 3 # Modulus (remainder of the division)
exponentiation = 2 ** 3 # Exponentiation
2. Comparison Operators:
Used to compare values and return Boolean results.
x = 5
y = 10
equal = x == y # Equal to
not_equal = x != y # Not equal to
greater_than = x > y # Greater than
less_than = x < y # Less than
greater_than_equal = x >= y # Greater than or equal to
less_than_equal = x <= y # Less than or equal to
3. Logical Operators:
Used to combine Boolean values.
a = True
b = False
logical_and = a and b # Logical AND
logical_or = a or b # Logical OR
logical_not = not a # Logical NOT
4. Assignment Operators:
Used to assign values to variables.
x = 5
x += 3 # Equivalent to x = x + 3
x -= 2 # Equivalent to x = x - 2
x *= 4 # Equivalent to x = x * 4
x /= 2 # Equivalent to x = x / 2
5. Membership Operators:
Used to test if a value is a member of a sequence (e.g., lists, tuples, strings).
numbers = [1, 2, 3, 4]
in_list = 3 in numbers # True
not_in_list = 5 not in numbers # True
6. Identity Operators:
Used to compare the memory locations of two objects.
a = [1, 2, 3]
b = [1, 2, 3]
is_equal = a == b # True (compares values)
is_identical = a is b # False (compares memory locations)
7. Bitwise Operators:
Used to perform bitwise operations on integers.
x = 5
y = 3
bitwise_and = x & y # Bitwise AND
bitwise_or = x | y # Bitwise OR
bitwise_xor = x ^ y # Bitwise XOR
bitwise_not = ~x # Bitwise NOT
left_shift = x << 1 # Left shift by 1 bit
right_shift = x >> 1 # Right shift by 1 bit
These are just some of the basic operators in Python. Understanding how to use operators is crucial for performing various operations in your programs, from simple arithmetic calculations to complex logical manipulations.