Python : Operators

In Python, operators are special symbols or keywords that are used to perform operations on operands. Operands can be variables, values, or expressions. Python supports various types of operators, including arithmetic operators, comparison operators, logical operators, assignment operators, and more. Let's go through each type of operator with examples:

1. Arithmetic Operators:

  •     : Addition

  •     : Subtraction

  •     : Multiplication

  •     / : Division

  •     % : Modulus (remainder)

  •     // : Floor division (quotient)

  •     ** : Exponentiation

Example:

a = 10
b = 3
print(a + b)    # Output: 13
print(a - b)    # Output: 7
print(a * b)    # Output: 30
print(a / b)    # Output: 3.3333333333333335
print(a % b)    # Output: 1
print(a // b)   # Output: 3
print(a ** b)   # Output: 1000

 

2. Comparison Operators:

  •     == : Equal to

  •     != : Not equal to

  •     < : Less than

  •     > : Greater than

  •     <= : Less than or equal to

  •     >= : Greater than or equal to

Example:

x = 5
y = 10
print(x == y)   # Output: False
print(x != y)   # Output: True
print(x < y)    # Output: True
print(x > y)    # Output: False
print(x <= y)   # Output: True
print(x >= y)   # Output: False

 

3. Logical Operators:

  •    and : Logical AND

  •    or : Logical OR

  •    not : Logical NOT

Example:

x = True
y = False
print(x and y)  # Output: False
print(x or y)   # Output: True
print(not x)    # Output: False

 

4. Assignment Operators:

  •    = : Assigns a value to a variable

  •    += , -=, *=, /=, %=, //=, **= : Perform the operation and assign the result to the variable

Example:

a = 10
a += 5   # Equivalent to: a = a + 5
print(a)  # Output: 15

 

5. Identity Operators:

  •     is : Returns True if both variables are the same object

  •     is not : Returns True if both variables are not the same object

Example:

x = [1, 2, 3]
y = [1, 2, 3]
print(x is y)     # Output: False
print(x is not y) # Output: True

 

6. Membership Operators:

  •    in : Returns True if a sequence contains a specified value

  •   not in : Returns True if a sequence does not contain a specified value

Example:

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

 

These are some of the commonly used operators in Python. Understanding and using operators effectively is essential for writing concise and efficient code.