Operators in Python: Master 4 Essential Types

2024-07-26

Operators are the command words of the Python language. They instruct Python to perform specific actions on data, which is stored in variables. Think of variables as the ingredients, and operators as the instructions in a recipe.

Let’s dive into the fundamental types of operators you’ll use in Python: arithmetic, comparison, logical, and membership operators.

1. Arithmetic Operators

These are the operators you probably recognize from everyday math:

  • Addition: Combines two values.
  • Subtraction: Finds the difference.
  • Multiplication: Calculates the product.
  • Division: Calculates the quotient.
  • Exponentiation: Raises a number to a power.
  • Modulo: Returns the remainder after division.

Example:

result = 5 + 3 * 2  # result is 11 (order of operations applies)

2. Comparison Operators

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

  • Equal to (==): Checks if two values are equal.
  • Not equal to (!=): Checks if two values are different.
  • Greater than (>): Checks if the left value is larger than the right.
  • Less than (<): Checks if the left value is smaller than the right.
  • Greater than or equal to (>=): Checks if the left value is larger or equal.
  • Less than or equal to (<=): Checks if the left value is smaller or equal.

Example:

is_equal = 5 == 5   # True
is_greater = 10 > 3  # True

3. Logical Operators

Logical operators combine multiple Boolean expressions:

  • and: True only if both expressions are True.
  • or: True if at least one expression is True.
  • not: Reverses the truth value of the expression.

Example:

is_sunny = True
is_warm = False

good_weather = is_sunny and is_warm   # False
go_outside = is_sunny or is_warm     # True

4. Membership Operators

Membership operators check if a value exists within a sequence (e.g., a string, list, or tuple):

  • in: True if the value is found.
  • not in: True if the value is not found.

Example:

text = "Hello, world!"
is_in = "Hello" in text        # True

Frequently Asked Questions (FAQ)

1. What’s the difference between the assignment operator (=) and the equality operator (==)? The assignment operator = sets a variable's value, while the equality operator == compares two values.

2. How do I remember the order of operations in Python? The acronym PEMDAS or BODMAS helps: Parentheses, Exponents, Multiplication, Division, Addition, Subtraction.