What is Operator in Python | Types of Operators?

What is Operator?
  • Operators in Python are symbols used to perform operations on variables and values.
  • They allow you to manipulate data and variables.


Types of Operators in Python:

Arithmetic Operators: Perform mathematical operations.

Example:
a = 10
b = 5
print(a + b)   # Output: 15 (Addition)
print(a - b)   # Output: 5 (Subtraction)
print(a * b)   # Output: 50 (Multiplication)
print(a / b)   # Output: 2.0 (Division)
print(a % b)   # Output: 0 (Modulus)


Comparison Operators: Compare values and return a boolean result.

Example:
a = 10
b = 5
print(a == b)   # Output: False (Equal to)
print(a != b)   # Output: True (Not equal to)
print(a > b)  # Output: True (Greater than)
print(a < b)  # Output: False (Less than)


Logical Operators: Perform logical operations (AND, OR, NOT).

Example:
a = True
b = False
print(a and b)  # Output: False (AND)
print(a or b)   # Output: True (OR)
print(not a)    # Output: False (NOT)


Assignment Operators: Assign values to variables.

Example:
a = 10
a += 5   # Same as a = a + 5
print(a)  # Output: 15

a = 10
a -= 3   # Same as a = a - 3
print(a)  # Output: 7


Increment/Decrement Operators: Increase or decrease the value of a variable.

Example:
a = 10
a += 1   # Increment by 1
print(a)  # Output: 11

a = 10
a -= 1   # Decrement by 1
print(a)  # Output: 9


Bitwise Operators: Perform bit-level operations.

Example:
a = 5   # Binary: 0101
b = 3   # Binary: 0011
print(a & b)  # Output: 1 (Bitwise AND)
print(a | b)  # Output: 7 (Bitwise OR)
print(a ^ b)  # Output: 6 (Bitwise XOR)


Membership Operators: Test membership in a sequence.

Example:
a = [1, 2, 3]
print(2 in a)   # Output: True
print(4 not in a)   # Output: True


Identity Operators: Compare memory locations of two objects.

Example:
a = [1, 2, 3]
b = a
print(a is b)   # Output: True
print(a is not b)   # Output: False

Post a Comment

0 Comments