DSM
50 XP
25 minsBeginner50 XP

Operators & Expressions

You can store a value and clean text. Now you'll make values interact: add them, compare them, and test conditions. Every calculation, every 'keep this row, drop that one' decision in data work starts here — with operators.

What you'll learn

  • Use arithmetic operators, including // floor division, % modulo, and ** power
  • Compare values with ==, !=, >, <, >=, <= to produce booleans
  • Combine conditions with and, or, and not
  • Predict results using operator precedence and clarify with parentheses
  • Read chained comparisons like 0 <= score <= 100

What

An operator is a symbol that acts on values (+, >, and). An expression is any combination of values and operators that Python evaluates down to a single result — a number, or a True/False.

Why

Analysis is arithmetic plus logic. You compute revenue with arithmetic operators and you decide which customers are 'high value' with comparison and logical operators. Expressions are the sentences of that language.

Where it's used

Totals, averages, and growth rates; the True/False tests that later become row filters; validation rules; and every condition your programs will branch on.

Where this runs in production

AmazonFree-shipping threshold

A cart qualifies when subtotal >= 35 and is_prime is False — a single logical expression decides whether the shipping fee is added.

DuolingoStreak-freeze eligibility

The app checks streak_days > 0 and gems >= 200 before offering a streak freeze — two comparisons joined with and.

RobinhoodPrice-alert triggers

An alert fires when price <= target_price, a comparison that evaluates to a bool checked against live market data.

Theory

The core ideas, in plain language.

Operators come in families. Arithmetic operators produce numbers. Comparison operators produce a bool (True or False). Logical operators combine bools. Assignment operators store results back into variables. Knowing which family an operator belongs to tells you what kind of value the expression will produce.
Key Concept
The arithmetic operators

+ add, - subtract, * multiply, / true divide (always gives a float: 6 / 2 is 3.0), // floor divide (drops the remainder: 7 // 2 is 3), % modulo (the remainder: 7 % 2 is 1), ** power (2 ** 3 is 8). Floor division and modulo are the two beginners overlook — and the two you'll use constantly for grouping and 'every Nth' logic.

Analogy: // and % are sharing pizza slices

You have 7 slices and 2 friends. 7 // 2 = 3 is how many whole slices each friend gets. 7 % 2 = 1 is how many slices are left over on the table. Floor division is the fair share; modulo is the remainder.

Key Concept
Comparison operators return booleans

== equal, != not equal, > greater, < less, >= at least, <= at most. Every comparison evaluates to True or False. Note the double == for comparison — a single = assigns. This is the boolean 'seed' that later grows into row filters.

Logical operators join booleans. `and` is True only when BOTH sides are True. `or` is True when AT LEAST ONE side is True. `not` flips a bool. So (score >= 60) and (attendance >= 0.8) is True only when a student clears both bars.
Analogy: and is a strict bouncer, or is a lenient one

Picture a club door. The 'and' bouncer lets you in only if you satisfy every rule — ID and dress code and on the list. The 'or' bouncer is easygoing: satisfy any one rule and you're in. 'not' is the bouncer who does the opposite of whatever the sign says.

score = 82
attendance = 0.9
passed = score >= 60 and attendance >= 0.8
print(passed)          # True
print(60 <= score <= 100)  # True  (chained comparison)
print(not passed)      # False

score >= 60 and attendance >= 0.8 reads left to right and returns one bool. Python also allows chained comparisons like 60 <= score <= 100, which mean exactly what they look like in maths — no need to write it as two separate conditions joined by and.

Watch out
Assignment operators are shortcuts, not comparisons

total += 5 means total = total + 5. The family includes -=, *=, /=, //=, %=, **=. They modify a variable in place. Do not confuse += (update) with == (compare) — they are unrelated.

Visual Learning

See the concept, then explore it.

How Python Evaluates an Expression

Click each stage to trace how 'price * qty > budget and in_stock' collapses to a single True or False.

Worked Examples

Watch it built up, one line at a time.

Very EasyTotal the items in a cart

A customer buys 6 notebooks at $3 each. Compute the total.

Step 1 of 3

Two integer variables — the unit price and how many were bought.

Code
01price = 3
02quantity = 6
Practice Coding

Your turn — write the code.

Your task

An online store evaluates one order. Complete the expressions below. Use the operator families you've learned — do not hard-code the True/False results.

Expected output
Total with fee: 89.0
Free shipping: True
Bulk member: True
Avg price: 12.0

Write your solution in the editor on the right, then hit Run.

Exercises

Prove it. Reach 80% to complete the lesson.

Mastery Gate0% / 80% required
Easy0/2 solved

What does 17 % 5 evaluate to?

What is the type of the result of the expression 8 > 3?

Medium0/3 solved

What does 2 + 3 * 4 ** 2 evaluate to?

ScenarioYou want to keep customers who are between 18 and 65 years old (inclusive). You have a variable age and need one boolean expression.

Which expression is correct AND idiomatic Python?

A store gives a discount only when an order is large AND the customer is a member. Given subtotal = 120, is_member = True, and a threshold of 100, print whether the discount applies (a single boolean). Expected output: True

Uses a logical AND:Both the size condition and membership must hold.
Prints a boolean:Output must be True, not a number or string.
Hard0/1 solved

A total of 100 cookies is packed into boxes of 8. Print how many FULL boxes there are and how many cookies are left over, on one line as 'boxes leftover'. Use floor division and modulo. Expected output: 12 4

Uses floor division:100 // 8 must give 12 full boxes.
Uses modulo:100 % 8 must give 4 leftover cookies.
Complete 80% more exercises to unlock.
Interview Prep

How this shows up in real interviews.

What's the difference between / and // in Python, and when would you use each?

Show model answer

/ is true division and always returns a float, even when the result is whole: 6 / 2 is 3.0, not 3. // is floor division, which divides and discards the fractional part, returning the largest whole number at or below the true result: 7 // 2 is 3. I use / for ordinary averages and rates where I want the decimals, and // whenever I need whole groupings — how many full boxes, pages, or batches — usually alongside % (modulo) to get the leftover. A subtle point is that // floors toward negative infinity, so -7 // 2 is -4, not -3.

Explain how operator precedence works in a mixed expression, and why you'd still use parentheses.

Show model answer

Python evaluates in a fixed order: ** first, then * / // %, then + and -, then comparison operators, then not, then and, then or. So 2 + 3 * 4 is 14 because * binds tighter than +, and a or b and c evaluates b and c first. Precedence means the code is unambiguous to the interpreter — but not always to a human reader. I add parentheses even when they're technically redundant because they make intent obvious and prevent the classic bugs, like writing a + b + c / 3 when I meant (a + b + c) / 3. Parentheses cost nothing at runtime and save review time.

How do and, or, and not evaluate, and what is short-circuiting?

Show model answer

'and' is True only if both operands are truthy; 'or' is True if at least one is; 'not' inverts. Crucially, Python short-circuits: for a and b, if a is falsy Python never even evaluates b, because the result is already determined; for a or b, if a is truthy it skips b. This matters for correctness and safety — you can write something like x != 0 and total / x > 1, and the division is only attempted when x isn't zero. Short-circuiting also means the operators return one of the actual operands, not always a strict bool, which is a common gotcha when the operands aren't booleans.

Common Mistakes to Avoid

1) Writing = where you mean == inside a condition — = assigns, == compares, and mixing them is a classic bug. 2) Forgetting precedence: a + b + c / 3 divides only c; wrap the sum in parentheses. 3) Assuming / gives a whole number — 6 / 2 is 3.0 (a float); use // when you want an integer count. 4) Reaching for & and | (which are bitwise operators) instead of the logical and / or on plain booleans. 5) Over-using 'or' in range checks: age > 18 or age < 65 is True for almost everyone — you almost always want 'and', or better, the chained form 18 <= age <= 65.

Ask the AI Tutor

Try these prompts in the AI Tutor panel: • 'ELI5: what's the difference between % and //?' • 'Quiz me on operator precedence with five tricky expressions.' • 'Show me a real bug caused by missing parentheses in an average.' • 'Give me three business rules and let me write the boolean expression for each.' • 'Interview mode: ask me to explain short-circuiting in and/or and grade my answer.'

Glossary

Operator — a symbol that acts on values (+, >, and). Expression — a combination of values and operators that evaluates to one result. Arithmetic operators — + - * / // % **. Floor division (//) — divide and drop the remainder. Modulo (%) — the remainder of a division. Comparison operators — == != > < >= <=, each returning a bool. Logical operators — and, or, not, combining booleans. Assignment operators — =, +=, -=, etc., that store a value into a variable. Operator precedence — the fixed order Python applies operators in. Chained comparison — a range test like 0 <= x <= 100. Short-circuiting — Python skipping the second operand of and/or when the result is already known.

Recommended Resources

• Docs: the Python reference section 'Operator precedence' lists every operator from tightest to loosest binding. • Read: 'Boolean Operations — and, or, not' in the standard-types docs explains short-circuiting from the source. • Practice: predict the result of five mixed expressions on paper, then check each in a REPL until precedence feels automatic. • Next in DSM: your comparisons produce booleans and your data often arrives as text — next you'll convert between types cleanly in Type Conversion.

Recap

✓ Arithmetic operators produce numbers; // floors and % gives the remainder. ✓ Comparison operators (== != > < >= <=) always produce a bool. ✓ Logical operators and/or/not combine booleans; and needs both, or needs one. ✓ Precedence runs ** then * / // % then + - then comparisons then not/and/or — parentheses override it. ✓ Chained comparisons like 18 <= age <= 65 read like maths and include both ends. ✓ These booleans are the exact seeds of the row filters you'll write later. Next up: Type Conversion. Your comparisons and maths assume the right types — next you'll turn strings from files and inputs into the numbers these operators need.

scratchpad — preview this lesson's challenge anytime
order_check.pyPython
Ready
Output

Run your code to see the output here.