Skip to main content

Comparison and Logical Operators

Comparison and Logical Operators

Introduction

Operators let you compare values and combine conditions. The results are always True or False, making them essential for controlling the flow of your programs.

Comparison Operators

These compare two values and return a boolean.

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than10 > 5True
>=Greater than or equal to5 >= 5True
<Less than3 < 10True
<=Less than or equal to4 <= 3False

Examples

salary = 60000

print(salary > 50000) # True
print(salary == 60000) # True
print(salary != 60000) # False
print(salary < 40000) # False

Logical Operators

Logical operators combine multiple conditions.

OperatorMeaningExampleResult
andBoth must be TrueTrue and FalseFalse
orAt least one must be TrueTrue or FalseTrue
notInverts the resultnot TrueFalse

Examples

salary = 60000
department = "Engineering"

print(salary > 50000 and department == "Engineering") # True
print(salary > 80000 or department == "Engineering") # True
print(not salary > 80000) # True

Membership Operators

Check whether a value exists in a sequence.

OperatorMeaningExampleResult
inValue is in the sequence"Alice" in ["Alice", "Bob"]True
not inValue is not in the sequence5 not in [1, 2, 3]True
approved_departments = ["Engineering", "Finance", "HR"]
department = "Engineering"

print(department in approved_departments) # True
print("Marketing" not in approved_departments) # True

Arithmetic Operators

OperatorMeaningExampleResult
+Addition10 + 515
-Subtraction10 - 55
*Multiplication10 * 550
/Division10 / 33.333...
//Floor division10 // 33
%Modulo (remainder)10 % 31
**Exponent2 ** 8256

Practice Exercises

  • Check whether a salary of 55000 is greater than 50000 and less than 100000. Print the result.
  • Create two variables is_employed and has_contract. Set one to True and one to False. Print whether both are True, and whether at least one is True.
  • Check if the string "python" is in the list ["sql", "python", "java"].
  • Calculate the remainder when 17 is divided by 5.

Enjoying the course? Found this useful? Check out the blog for more deep dives on data engineering and software.