Python: lesson 3 of 7

Python

PATH 01MODULE 02LESSON 03 OF 07Next: Conditional Statements

Operators and Expressions

Use arithmetic, comparisons, and logical conditions to calculate and reason about data.

Beginner13 min readpythonoperatorsexpressionsmetrics

Concept

Operators are symbols or words that tell Python to perform an action. An expression combines values, variables, and operators to produce a new value. revenue / orders is an expression; > compares values; and combines conditions.

Why It Matters

Data work is full of expressions: calculating a conversion rate, comparing a score to a threshold, or deciding whether a record meets several quality rules. Understanding the small pieces makes later filtering and feature engineering easier to read.

Intuition

An operator is a verb in a compact sentence. Arithmetic operators calculate, comparison operators ask a question, and logical operators combine answers to questions.

Arithmetic and Assignment

completed_orders = 84
website_visits = 1200
conversion_rate = completed_orders / website_visits

completed_orders += 1
print(conversion_rate)
print(completed_orders)

Expected output:

0.07
85

The common arithmetic operators are +, -, *, /, // for floor division, % for remainder, and ** for powers. Assignment operators such as += update a variable using its current value.

Real-World / Data Science Example

An analyst may want to identify a model that is both accurate enough and fast enough for a product requirement.

model_accuracy = 0.91
prediction_latency_ms = 80

meets_accuracy_target = model_accuracy >= 0.90
meets_latency_target = prediction_latency_ms < 100
is_candidate = meets_accuracy_target and meets_latency_target

print(is_candidate)

Expected output:

True

Comparison operators include ==, !=, <, <=, >, and >=. They return Boolean values. Use == to compare values; = assigns a value.

Logical and Membership Operators

and requires both conditions to be true, or requires at least one, and not reverses a Boolean value. Membership operators ask whether a value is contained in a collection.

country = "India"
allowed_countries = ["India", "Singapore", "Australia"]
has_valid_country = country in allowed_countries

is_missing = None is None
print(has_valid_country, is_missing)

Expected output:

True True

Use is None when checking for None, rather than == None.

Operator Precedence

Python evaluates multiplication and division before addition and subtraction. Parentheses make the intended calculation clear.

revenue = 1000
cost = 600
margin_rate = (revenue - cost) / revenue
print(margin_rate)

Expected output: 0.4. Parentheses are valuable even when you know the precedence, because they document the business calculation.

Explanation of the Code

The conversion-rate expression divides completed orders by visits. The model example first assigns each requirement a readable Boolean name, then joins the two decisions with and. This is clearer than placing a long condition everywhere it is needed.

When to Use It

Use arithmetic for derived metrics, comparisons for rules and thresholds, logical operators for multiple requirements, and membership for known lists of allowed values. In Pandas, the same ideas appear as vectorized comparisons over an entire column.

Failure Signals

Common Mistakes

  1. Using = instead of == in a comparison.
  2. Dividing by zero without checking the denominator.
  3. Forgetting parentheses in a business metric.
  4. Writing a long condition without intermediate Boolean names.

Best Practices

Name thresholds and intermediate conditions. Make units clear in names, such as latency_ms. For rates, confirm whether the denominator can be zero and what should happen if it is. Prefer explicit parentheses for calculations that may be reviewed by others.

Data Science Perspective

Operators power filtering, metric computation, validation rules, and feature creation. You will use the same logic to create Pandas masks, compare model scores, and define conditions for data cleaning. For large tables, later tools apply these operations to many values at once.

Interview Perspective

Question: What is the difference between = and ==? A strong answer: = assigns a value to a name; == compares two values and returns True or False.

Worked Example: Make a Metric Rule Explicit

Metrics should be named before they become decisions. This separates the calculation from the operating rule.

true_positives = 42
false_positives = 8
precision = true_positives / (true_positives + false_positives)
minimum_precision = 0.80

should_review_model = precision >= minimum_precision
print(precision, should_review_model)

Expected output: 0.84 True. The denominator matters: precision asks how often positive predictions were correct, not how many positives the model found overall.

Practice Questions

  1. Calculate average revenue from total_revenue and customer_count.
  2. Write an expression that is true when precision is at least 0.8 and recall is at least 0.7.
  3. Explain why (revenue - cost) / revenue is clearer than relying on precedence.

Quick Quiz

  1. What does 5 % 2 return? Answer: 1.
  2. What does "Pandas" in ["Python", "Pandas"] return? Answer: True.
  3. What does not True return? Answer: False.

Key Takeaway

Key Takeaways

Operators turn raw values into calculations and decisions. Use readable intermediate names and parentheses to make analytical logic easier to verify.

Next Lesson

Next, use Boolean expressions inside conditional statements to choose different actions.

Finish this lesson on your terms

Mark it complete when you have worked through the material and are ready to move on.