fbpx

Operators and Expressions in Python


1. Arithmetic Operators:

Arithmetic operators perform mathematical operations.

# Addition
result_addition = 5 + 3

# Subtraction
result_subtraction = 10 - 4

# Multiplication
result_multiplication = 2 * 6

# Division
result_division = 8 / 2

# Modulus (remainder)
remainder = 10 % 3

# Exponentiation
result_exponentiation = 2 ** 3

2. Comparison Operators:

Comparison operators are used to compare values and return a Boolean result.

x = 10
y = 5

# Equal to
is_equal = x == y

# Not equal to
not_equal = x != y

# Greater than
greater_than = x > y

# Less than
less_than = x < y

# Greater than or equal to
greater_than_or_equal = x >= y

# Less than or equal to
less_than_or_equal = x <= y

3. Logical Operators:

Logical operators perform logical operations and return a Boolean result.

a = True
b = False

# Logical AND
logical_and = a and b

# Logical OR
logical_or = a or b

# Logical NOT
logical_not = not a

4. Assignment Operators:

Assignment operators assign values to variables.

total = 0

# Addition assignment
total += 5  # Equivalent to total = total + 5

# Subtraction assignment
total -= 3  # Equivalent to total = total - 3

# Multiplication assignment
total *= 2  # Equivalent to total = total * 2

# Division assignment
total /= 4  # Equivalent to total = total / 4

5. Identity Operators:

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

x = [1, 2, 3]
y = [1, 2, 3]
z = x

# is (True if both variables point to the same object)
is_same_object = x is z

# is not (True if both variables do not point to the same object)
is_not_same_object = x is not y

6. Membership Operators:

Membership operators test whether a value is a member of a sequence (e.g., list, tuple, string).

numbers = [1, 2, 3, 4, 5]

# in (True if the value is found in the sequence)
is_present = 3 in numbers

# not in (True if the value is not found in the sequence)
is_not_present = 6 not in numbers

7. Bitwise Operators:

Bitwise operators perform operations on individual bits of binary numbers.

# 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 << 1

# Bitwise right shift
result_right_shift = 5 >> 1

Expressions:

An expression is a combination of values, variables, and operators that can be evaluated to produce a result.

# Arithmetic expression
result = (3 + 4) * 2

# Comparison expression
is_greater = 5 > 3

# Logical expression
is_valid = (age >= 18) and (has_license or is_student)

Understanding operators and expressions is essential for performing calculations, making decisions, and controlling the flow of a Python program. In the next sections, we’ll explore how to use these concepts in real-world scenarios and applications.