Mastering Basic Operators in Python

Learn Python @ Freshers.in

Python’s basic operators are essential tools for performing various operations on data. In this comprehensive guide, we will explore Python’s basic operators in detail, covering arithmetic, comparison, logical, assignment, identity, membership, and bitwise operators. Through real-world examples and outputs, you’ll gain a deep understanding of how to wield these operators effectively in Python programming.

1. Arithmetic Operators

Arithmetic operators allow you to perform mathematical operations like addition, subtraction, multiplication, division, and more.

Example:

# Addition
result_add = 5 + 3

# Subtraction
result_sub = 10 - 4

# Multiplication
result_mul = 6 * 7

# Division
result_div = 15 / 3

# Modulus (remainder)
result_mod = 17 % 5

# Exponentiation
result_exp = 2 ** 4

2. Comparison Operators

Comparison operators are used to compare values and return Boolean results.

Example:

# Equal to
is_equal = 5 == 5

# Not equal to
is_not_equal = 10 != 5

# Greater than
is_greater = 15 > 10

# Less than
is_less = 3 < 7

# Greater than or equal to
is_greater_equal = 20 >= 20

# Less than or equal to
is_less_equal = 12 <= 8

3. Logical Operators

Logical operators allow you to combine multiple conditions.

Example:

# Logical AND
is_valid = True and True

# Logical OR
is_accepted = True or False

# Logical NOT
is_invalid = not True

4. Assignment Operators

Assignment operators are used to assign values to variables.

Example:

# Assign value
x = 5

# Add and assign
x += 3

# Subtract and assign
x -= 2

# Multiply and assign
x *= 4

5. Identity Operators

Identity operators are used to compare the memory locations of objects.

Example:

# is (True if both variables point to the same object)
x = [1, 2, 3]
y = x
are_identical = x is y

# is not (True if both variables point to different objects)
z = [1, 2, 3]
are_not_identical = x is not z

6. Membership Operators

Membership operators are used to test if a sequence is presented in an object.

Example:

# in (True if a sequence is found in the object)
fruits = ["apple", "banana", "cherry"]
is_in_list = "banana" in fruits

# not in (True if a sequence is not found in the object)
is_not_in_list = "orange" not in fruits

7. Bitwise Operators

Bitwise operators manipulate bits of integers.

Example:

# Bitwise AND
result_and = 5 & 3

# Bitwise OR
result_or = 5 | 3

# Bitwise XOR
result_xor = 5 ^ 3

# Bitwise NOT
result_not = ~5

# Bitwise left shift
result_left_shift = 5 << 2

# Bitwise right shift
result_right_shift = 5 >> 2
Author: user