Python - Operators

In Python, operators are symbols or special characters that represent an action or operation to be performed on one or more operands. Here are some of the most commonly used operators in Python:

  • Arithmetic Operators:
    • Addition (+): adds two values together
    • Subtraction (-): subtracts one value from another
    • Multiplication (*): multiplies two values together
    • Division (/): divides one value by another
    • Modulus (%): returns the remainder after division
    • Exponent (**): raises a value to a power
  • Comparison Operators:
    • Equal to (==): returns True if two values are equal
    • Not equal to (!=): returns True if two values are not equal
    • Greater than (>): returns True if the first value is greater than the second value
    • Less than (<): returns True if the first value is less than the second value
    • Greater than or equal to (>=): returns True if the first value is greater than or equal to the second value
    • Less than or equal to (<=): returns True if the first value is less than or equal to the second value
  • Logical Operators:
    • And (and): returns True if both conditions are True
    • Or (or): returns True if at least one condition is True
    • Not (not): returns the opposite of the condition (True becomes False, and vice versa)
  • Assignment Operators:
    • Equal to (=): assigns a value to a variable
    • Add and assign (+=): adds a value to a variable and assigns the result to the variable
    • Subtract and assign (-=): subtracts a value from a variable and assigns the result to the variable
    • Multiply and assign (*=): multiplies a variable by a value and assigns the result to the variable
    • Divide and assign (/=): divides a variable by a value and assigns the result to the variable
    • Modulus and assign (%=): calculates the modulus of a variable and a value and assigns the result to the variable
    • Exponent and assign (**=): raises a variable to a power and assigns the result to the variable
  • Bitwise Operators:
    • Bitwise AND (&): performs a bitwise AND operation on two values
    • Bitwise OR (|): performs a bitwise OR operation on two values
    • Bitwise XOR (^): performs a bitwise XOR operation on two values
    • Bitwise NOT (~): performs a bitwise NOT operation on a value
    • Left shift (<<): shifts the bits of a value to the left by a specified number of positions
    • Right shift (>>): shifts the bits of a value to the right by a specified number of positions
  • Identity Operators:
    • Is (is): returns True if two variables refer to the same object in memory
    • Is not (is not): returns True if two variables do not refer to the same object in memory
  • Membership Operators:
    • In (in): returns True if a value is found in a sequence
    • Not in (not in): returns True if a value is not found in a sequence