Labs ICT
โญ Pro Login

Operators

Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations on numbers.

x = 15
y = 4

print(x + y)   # Addition: 19
print(x - y)   # Subtraction: 11
print(x * y)   # Multiplication: 60
print(x / y)   # Division: 3.75
print(x // y)  # Floor Division: 3
print(x % y)   # Modulus (remainder): 3
print(x ** y)  # Exponentiation: 50625

Note: Floor division (//) rounds down to the nearest integer. Modulus (%) returns the remainder after division.

Comparison Operators

Comparison operators compare two values and return a Boolean result (True or False).

a = 10
b = 20

print(a == b)  # Equal to: False
print(a != b)  # Not equal to: True
print(a > b)   # Greater than: False
print(a < b)   # Less than: True
print(a >= b)  # Greater than or equal to: False
print(a <= b)  # Less than or equal to: True

Chained Comparisons

x = 5
print(1 < x < 10)   # True
print(1 < x < 3)    # False
print(10 > x >= 5)  # True

Logical Operators

Logical operators combine conditional statements.

x = True
y = False

print(x and y)  # AND: False
print(x or y)   # OR: True
print(not x)    # NOT: False

Practical Examples

age = 25
has_license = True

# Both conditions must be True
if age >= 18 and has_license:
    print("You can drive")

# At least one condition must be True
is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
    print("Day off!")

# Reverses the boolean value
is_raining = False
if not is_raining:
    print("No umbrella needed")

Membership Operators

Membership operators test if a value is found in a sequence (string, list, tuple, set, dictionary).

fruits = ["apple", "banana", "cherry"]

print("banana" in fruits)      # True
print("grape" not in fruits)   # True

# With strings
text = "Hello, World!"
print("World" in text)     # True
print("world" in text)     # False (case-sensitive)

Identity Operators

Identity operators compare the memory locations of two objects.

a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a is b)      # False (different objects)
print(a is c)      # True (same object)
print(a is not b)  # True

# Use == for value comparison, is for identity comparison
print(a == b)      # True (same values)

Note: Use is to check if two variables point to the same object in memory. Use == to check if values are equal.

๐Ÿงช Quick Quiz

Which operator is used for exponentiation in Python?