5. Operators

5. Operators

Python supports various types of operators for performing operations on variables and values:

  1. Arithmetic Operators:

  • Addition (+), Subtraction (-), Multiplication (*), Division (/)

  • Floor Division (//), Modulus (%), Exponentiation (**)

  1. Comparison Operators:

  • Equal to (==), Not equal to (!=)

  • Greater than (>), Less than (<)

  • Greater than or equal to (>=), Less than or equal to (<=)

  1. Logical Operators:

  • and, or, not

  1. Assignment Operators:

  • =, +=, -=, *=, /=, %=, **=, //=

  1. Bitwise Operators:

  • & (AND), | (OR), ^ (XOR), ~ (NOT)

  • << (left shift), >> (right shift)

# Example code:

# Arithmetic operators
a, b = 10, 3
print(f"a + b = {a + b}")  # Addition
print(f"a - b = {a - b}")  # Subtraction
print(f"a * b = {a * b}")  # Multiplication
print(f"a / b = {a / b}")  # Division
print(f"a // b = {a // b}")  # Floor division
print(f"a % b = {a % b}")  # Modulus
print(f"a ** b = {a ** b}")  # Exponentiation

# Comparison operators
print(f"a == b: {a == b}")
print(f"a != b: {a != b}")
print(f"a > b: {a > b}")
print(f"a < b: {a < b}")

# Logical operators
x, y = True, False
print(f"x and y: {x and y}")
print(f"x or y: {x or y}")
print(f"not x: {not x}")

# Assignment operators
c = 5
c += 2  # Equivalent to c = c + 2
print(f"c after c += 2: {c}")

# Bitwise operators
d, e = 60, 13  # 60 = 0011 1100, 13 = 0000 1101
print(f"d & e: {d & e}")  # AND
print(f"d | e: {d | e}")  # OR
print(f"d ^ e: {d ^ e}")  # XOR
print(f"~d: {~d}")  # NOT
print(f"d << 2: {d << 2}")  # Left Shift
print(f"d >> 2: {d >> 2}")  # Right Shift

Last updated