Operators

Operators

ยท

3 min read

Python offers a wide range of operators that help developers write efficient code. This article provides an overview of operators in Python.

Arithmetic Operators

Arithmetic operators in Python perform mathematical operations. Here are the arithmetic operators in Python:

For instance, if you want to add two numbers, you can use the + operator as shown below:

a = 3
b = 4
c = a + b
print(c)  # prints 7

Comparison Operators

In Python, comparison operators are used to compare values. They return a boolean value of either True or False. Here are the comparison operators:

For example, consider the following code that compares two variables:

a, b = 5, 10
print(a == b)    # Output: False
print(a != b)    # Output: True

Logical Operators

Logical operators in Python are used to combine conditional statements. They return a boolean value of either True or False. Logical operators are and, or, and not.

x = 4
result1 = (x < 6) and (x > 2)
print(result1)  # Output: True

result2 = (x > 10) or (x % 2 == 0)
print(result2)  # Output: True

result3 = not (x < 6)
print(result3)  # Output: False

Bitwise Operators

Bitwise operators are used to carry out bit-by-bit manipulation of binary data. Here are the bitwise operators in Python:

a = 60    # 0011 1100
b = 13    # 0000 1101
c = a & b # 0000 1100
d = a | b # 0011 1101
print(c)  # prints 12
print(d)  # prints 61

Assignment Operators

Python also offers assignment operators to assign values to variables. Here are the assignment operators:

a = 10
b = 2
a += b    # Equivalent to: a = a + b
print(a)  # Output: 12
a -= b    # Equivalent to: a = a - b
print(a)  # Output: 10
a *= b    # Equivalent to: a = a * b
print(a)  # Output: 20

Identity and Membership Operators

In Python, identity and membership operators provide powerful tools for comparing and manipulating data.

Identity Operators:

  • is: Tests if two objects have the same identity, meaning they refer to the same memory location.

  • is not: Tests if two objects have different identities, indicating they do not refer to the same memory location.

Membership Operators:

  • in: Checks if a value is present in a sequence, such as a list, tuple, or string.

  • not in Checks if a value is not present in a sequence.

Comparing Operators(is vs ==)

  • An is expression evaluates to True if two variables point to the same object.

  • An == expression evaluates to True if the objects or value are equal (have the same value).

      x = [1, 2, 3]
      y = [1, 2, 3]
      z = x
    
      print(x == y)   # Output: True
      print(x is z)  # Output: True (Same object)
      print(x is y)  # Output: False (x,y Different objects)
    

In conclusion, Python offers a wide range of operators that help developers write clean and efficient code. Understanding how to use these operators is crucial for programming in Python.

ย