Table of Contents

Understanding operator precedence is essential to writing correct and predictable Python expressions. Just like in math, Python follows specific rules to determine the order in which parts of an expression are evaluated. Without mastering these rules, it's easy to misinterpret how a complex expression will behave. Operator precedence affects everything from arithmetic calculations to logical evaluations and function calls.

In the tasks below, you'll practice how different operators interact with one another when used in the same expression. You’ll also learn how to use parentheses effectively to control evaluation order and avoid logic errors.

What you should know:

Beginner-Level Practice - Operator Precedence

These beginner-level tasks are designed to help you get comfortable with how Python evaluates simple expressions involving multiple operators. You’ll explore how multiplication, addition, comparisons, and logical operations are prioritized, and how parentheses can be used to influence the result. These scenarios are short but important for avoiding mistakes in real-world code such as calculations, conditions, and loops.

1. Simple Calculation Trap

Ask the user to enter two integers: hours worked and hourly rate. Then print the weekly salary using the formula: salary = hours * rate + 50. But here's the twist — explain why the result may differ if parentheses are added around (hours * rate). Print both versions of the salary and compare them.

What this Task Teaches

This task introduces the basics of arithmetic operator precedence and how adding parentheses changes the evaluation of expressions. You’ll learn that multiplication takes precedence over addition, and how to make that order explicit using parentheses for clarity and safety in financial or numerical code.

Hints and Tips

Remember that * has higher precedence than +. Compare two expressions — one with and one without parentheses — and print both results to see the difference.

  • Use input() and int() for user data
  • Calculate hours * rate + 50
  • Then calculate (hours * rate) + 50 explicitly
Common Mistakes
  1. Not using parentheses when needed: Beginners often forget how default order affects the final result.
  2. Confusing which operator comes first: Some assume addition is evaluated before multiplication.
  3. Assigning incorrect values: Placing the bonus outside the parentheses may lead to unintended results.
  4. Forgetting to cast input: Using strings in arithmetic will cause type errors.
  5. Comparing values incorrectly: Comparing string representations can also cause misleading outcomes.
Step-by-Step Thinking

Always break your expression into parts and check which operators apply first. If unsure, add parentheses for clarity.

  • Ask for hours and rate as integers
  • Calculate the first version: hours * rate + 50
  • Then add parentheses: (hours * rate) + 50
  • Print both results and explain the difference
  • Use comments to describe what happens in each case
How to Make it Harder
  • Allow the user to enter a custom bonus and apply it conditionally
  • Use float values instead of integers for rate
  • Add tax calculation with * and - operators

2. Can You Drink Coffee?

Create a small script that asks for two inputs: age and whether the person had coffee today (yes/no). Use an expression that checks whether the user is over 16 and hasn’t had coffee today. Use and and not in with comparisons, and add parentheses to change evaluation order. Output whether the person can drink more coffee based on the condition.

What this Task Teaches

This task explores the interaction between logical operators like and, not, and in within compound boolean expressions. You’ll learn how Python evaluates combined conditions and how parentheses can shift logical grouping — especially in decisions that involve more than two criteria.

Hints and Tips

Pay attention to the order in which not and and apply. Use parentheses to test variations in logic.

  • Use input() for age and coffee status
  • Check if age is over 16
  • Check if coffee input is "no"
  • Use and and not in in one line
  • Add parentheses to modify evaluation flow
Common Mistakes
  1. Not converting age to integer: All comparisons will fail if age is treated as a string.
  2. Misplacing not: not in has different precedence than expected — test carefully.
  3. Skipping parentheses: Without grouping, the logic may return the opposite result.
  4. Incorrect boolean logic: not age > 16 behaves differently than age <= 16.
  5. String comparison typos: Comparing “No” instead of “no” can break your condition.
Step-by-Step Thinking

When multiple conditions must be met, evaluate them one at a time, then group them logically.

  • Get user inputs for age and coffee
  • Convert age to integer and normalize text
  • Check age > 16
  • Check if coffee status is “no”
  • Combine conditions with and and use not properly
  • Test with and without parentheses
How to Make it Harder
  • Ask how many cups of coffee were consumed and limit the number
  • Support multiple conditions using or
  • Allow checking caffeine tolerance with an extra question

Intermediate-Level Practice - Operator Precedence

These tasks are designed to help you handle more complex expressions that combine arithmetic, comparison, and logical operators. At this level, you should start recognizing when a seemingly correct expression behaves differently due to Python’s precedence rules. You’ll work with multi-layered expressions, nested operations, and conditional logic that must be carefully structured to work as intended. Mastery here will help you avoid subtle bugs and ensure your code’s logic flows as expected in real-world applications like data filtering or decision-making.

1. Exam Result Checker

Write a program that asks a student to enter their three exam scores. The program should calculate the average and print whether they’ve passed. The rule is: the student passes if the average is above 70 or any individual score is above 90, and no score is below 50. Use a combination of and, or, and comparison operators. Add parentheses to control the evaluation properly.

What this Task Teaches

This task teaches how logical operators interact when combined with comparison expressions, especially in multi-part conditional checks. You'll learn how to group boolean expressions meaningfully and avoid incorrect logic that can result from misunderstood operator precedence. Parentheses are essential here for structuring readable, correct conditions in real-world validations.

Hints and Tips

Think about how or and and behave together: and has higher precedence than or. To ensure the correct logic, always use parentheses where needed.

  • Use input() and float() for exam scores
  • Calculate average score
  • Apply the pass/fail logic with nested conditions
  • Group average > 70 or score > 90 together
  • Ensure all scores are >= 50
Common Mistakes
  1. Misplacing parentheses: Without parentheses, and and or may not behave as expected, leading to students being marked incorrectly.
  2. Wrong operator grouping: Checking only the average or one score without properly nesting conditions can break the logic.
  3. Forgetting float conversion: Using input() without float() leads to string comparison errors.
  4. Hardcoding only one pass condition: Forgetting to apply the “no score under 50” check may falsely approve poor results.
  5. Incorrect logical logic: Using and instead of or in pass conditions gives overly strict evaluations.
Step-by-Step Thinking

In tasks involving multiple conditions, break down your logic into small decisions, then structure them with grouping to reflect correct evaluation order.

  • Ask the user to enter 3 scores
  • Convert scores to floats and store them
  • Calculate the average
  • Check if average > 70 or any score > 90
  • Also check that all scores are ≥ 50
  • Use parentheses to group conditions logically
  • Print pass/fail based on the final condition
How to Make it Harder
  • Support 5 exams instead of 3 using a loop
  • Include grade categories (A, B, C, Fail)
  • Track which condition triggered pass/fail

2. Parking Fee Calculator

Create a program that calculates parking fees. The user enters hours parked and whether they used a VIP parking spot (yes/no). Here’s the rule: if the hours are over 5 and the user is not a VIP, charge $20; otherwise, charge $10. Use boolean expressions involving and, not, and comparisons. Show how using parentheses affects the result and print a warning if the condition is evaluated incorrectly due to operator precedence.

What this Task Teaches

This task reinforces how operator precedence impacts boolean logic involving not and and. You will practice grouping expressions and clearly separating conditional branches, avoiding mistakes caused by assuming wrong evaluation order. The task mimics real-life billing or access control scenarios.

Hints and Tips

Remember that not has higher precedence than and. If your logic isn’t giving the right result, add parentheses to clarify the grouping.

  • Take user input for hours and VIP status
  • Convert hours to int
  • Check if hours > 5 and VIP is “no”
  • Use not and comparison carefully
  • Add parentheses and compare different outcomes
Common Mistakes
  1. Not grouping not VIP correctly: This may cause logic to apply to the wrong condition.
  2. Using not on the wrong part: not hours > 5 flips logic in an unintended way.
  3. Ignoring string comparison: Comparing with "Yes"/"No" case-sensitively may lead to mismatches.
  4. Skipping parentheses: Incorrect grouping can result in the wrong fee being charged.
  5. Inverting logic accidentally: Using or instead of and may allow incorrect discounts.
Step-by-Step Thinking

Treat the two parts of the condition separately, then decide whether grouping with and or using not first changes the logic.

  • Get the number of hours and VIP status
  • Convert hours to integer
  • Check if hours > 5 and not VIP
  • Use parentheses to ensure correct logic
  • Decide fee based on result and print it
How to Make it Harder
  • Handle more user types: VIP, guest, staff
  • Apply hourly rates with tiered logic
  • Print billing summary with tax and receipt

Advanced-Level Practice - Operator Precedence

At the advanced level, operator precedence must be mastered for crafting correct and maintainable logic in complex expressions. You will deal with deeply nested operations, chained comparisons, ternary expressions, and arithmetic embedded within logical checks. These tasks are similar to what developers face in data processing, filtering systems, or algorithm design — where a single misplaced parenthesis could break an entire function. Understanding evaluation order becomes essential for writing readable and bug-free code that behaves as expected.

1. Smart Discount Evaluator

You are building a system that applies one of three discount rules based on customer behavior. The user inputs three values: is_member (True/False), total_spent (number), and coupon_applied (True/False). Discounts are given as follows:

  • If the customer is a member and spent over $200, they get 20% off.
  • If the customer is not a member but applied a coupon and spent over $100, they get 10% off.
  • Otherwise, they get no discount.

Write a logic expression to choose the right discount and print the final amount. Be very careful with how and, or, and not are evaluated.

What this Task Teaches

This task teaches advanced conditional logic involving boolean flags and numerical thresholds. You will combine and, or, and not operators, while being mindful of their precedence. You'll also learn how to clearly group and prioritize logic using parentheses to prevent logical errors when evaluating customer eligibility.

Hints and Tips

Break the rules into separate logical blocks and group them using parentheses. Prioritize clarity and correct short-circuiting in your conditional expression.

  • Use and inside discount conditions
  • Use or to evaluate multiple eligibility paths
  • Watch out for not changing the meaning of a check
  • Consider using intermediate variables for readability
Common Mistakes
  1. Ignoring precedence of not: Applying not without parentheses can flip the wrong part of the condition, resulting in faulty discount logic.
  2. Overlooking grouping: Writing is_member and total_spent > 200 or coupon_applied and total_spent > 100 without parentheses gives incorrect results.
  3. Forgetting type conversion: If you take user input as string, comparisons like total_spent > 200 will silently fail.
  4. Wrong logical combinations: Using or where and is needed may allow unintended discounts.
  5. Incorrect final amount calculation: Always base your total calculation on the correctly chosen discount rate.
Step-by-Step Thinking

To design multi-branch logic, first map out each rule separately, then combine them using the right grouping strategy to ensure Python interprets them correctly.

  • Input: is_member (bool), total_spent (float), coupon_applied (bool)
  • Define three conditions for discount eligibility
  • Group each logical rule using parentheses
  • Evaluate the discount rate based on matched condition
  • Apply the discount to total and print final amount
How to Make it Harder
  • Introduce a loyalty tier system with tier-specific discount percentages
  • Add dynamic pricing where discount rate scales with amount spent
  • Include an audit log showing which condition was triggered

2. Access Authorization Engine

Build a small logic system that decides if a user is authorized to access a restricted resource. The system takes in the following inputs: is_admin (True/False), has_2fa (True/False), login_attempts (int). A user is authorized only if they are either:

  • An admin with 2FA enabled
  • A regular user with less than 3 login attempts and also has 2FA enabled

If none of these conditions apply, deny access. Use a single if-statement with nested and grouped expressions. Use clear parentheses to enforce operator precedence and short-circuiting logic.

What this Task Teaches

This task enhances your ability to combine comparison and boolean logic with clear grouping using parentheses. You’ll see how logical flow and operator priority impact access control logic in a security context. Proper use of short-circuit logic also becomes essential to avoid redundant evaluation and ensure clarity in branching.

Hints and Tips

Consider breaking the access conditions into two separate blocks and then combining them using or. Always use parentheses to control evaluation order.

  • Check if the user is an admin and has 2FA
  • Or: check if the user is not an admin, has 2FA, and login_attempts < 3
  • Use parentheses around each condition block
  • Ensure the logic does not allow unauthorized access due to missing grouping
Common Mistakes
  1. Incorrect grouping of conditions: Not using parentheses may lead to or overriding an intended and, granting access when it shouldn't.
  2. Misunderstanding short-circuit behavior: Python may skip checking a second condition, which can be problematic if logic relies on it.
  3. Hardcoding role logic: Trying to use one large flat expression without separating admin and user rules leads to unreadable and error-prone code.
  4. Mixing strings with booleans: Comparing input like "True" with boolean True fails silently — always convert properly.
  5. Redundant checks: Repeating the same condition more than once makes the logic inefficient and harder to debug.
Step-by-Step Thinking

Think like a security system: define roles and requirements, then encode them using grouped logic that prioritizes clarity and correctness.

  • Take in three inputs: is_admin (bool), has_2fa (bool), login_attempts (int)
  • Define admin rule: is_admin and has_2fa
  • Define regular user rule: not is_admin and has_2fa and login_attempts < 3
  • Combine both rules using or with parentheses
  • Print access granted or denied accordingly
How to Make it Harder
  • Add access levels: read, write, admin, with different rules
  • Use a function that takes multiple conditions and logs each check
  • Track failed access attempts with a counter and lockout feature

Author of This Exercises

Jason Miller

Jason Miller

I'm a seasoned Python backend developer with over six years of experience working...

Learn more →

Author of This Exercises

Sarah Jane Notli

Sarah Jane Notli

I'm a Senior Data Scientist at a Leading Tech Company in Silicon Valley...

Learn more →