Python Operators

www.igif‮oc.aedit‬m

Operators in Python are symbols that are used to perform operations on variables and values. Python supports a wide range of operators, including arithmetic, comparison, logical, assignment, identity, membership, and bitwise operators.

Arithmetic Operators:

  • + : Addition
  • - : Subtraction
  • * : Multiplication
  • / : Division (returns a float)
  • // : Division (returns an integer)
  • % : Modulo (returns the remainder)
  • ** : Exponentiation (raises a number to a power)

Comparison Operators:

  • == : Equal to
  • != : Not equal to
  • < : Less than
  • > : Greater than
  • <= : Less than or equal to
  • >= : Greater than or equal to

Logical Operators:

  • and : Returns True if both conditions are True
  • or : Returns True if at least one condition is True
  • not : Inverts the result, returns False if the result is True

Assignment Operators:

  • = : Assigns a value to a variable
  • += : Adds a value and assigns the result to a variable
  • -= : Subtracts a value and assigns the result to a variable
  • *= : Multiplies a value and assigns the result to a variable
  • /= : Divides a value and assigns the result to a variable
  • %=, //= , **= : Modulo, floor division, and exponentiation operators with assignment.

Identity Operators:

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

Membership Operators:

  • in : Returns True if a sequence with the specified value is present in the object
  • not in : Returns True if a sequence with the specified value is not present in the object

Bitwise Operators:

  • & : Bitwise AND
  • | : Bitwise OR
  • ^ : Bitwise XOR
  • ~ : Bitwise NOT
  • << : Bitwise left shift
  • >> : Bitwise right shift

Here are some examples of using operators in Python:

# Arithmetic Operators
x = 10
y = 3
print(x + y)  # output: 13
print(x - y)  # output: 7
print(x * y)  # output: 30
print(x / y)  # output: 3.3333333333333335
print(x // y)  # output: 3
print(x % y)  # output: 1
print(x ** y)  # output: 1000

# Comparison Operators
a = 5
b = 7
print(a == b)  # output: False
print(a != b)  # output: True
print(a < b)  # output: True
print(a > b)  # output: False
print(a <= b)  # output: True
print(a >= b)  # output: False

# Logical Operators
c = True
d = False
print(c and d)  # output: False
print(c or d)  # output: True
print(not c)  # output: False

# Assignment Operators
e = 10
e += 5  # equivalent to e = e + 5
print(e)  # output: 15

# Identity Operators
f = [1, 2, 3]
g = [1, 2, 3