Operators and Expressions
Explore how Python operators transform data through arithmetic, comparison, and logical expressions. Understand operator precedence and grouping to write clear, correct code that models real-world scenarios and decision logic in your programs.
We'll cover the following...
We have learned how to store data in variables, but storing alone isn’t enough. To build software, whether it is a game, a financial calculator, or a data analysis script, we need to transform that data. Operators are the verbs of programming that allow us to combine, modify, and compare values to create new information. In this lesson, we will explore how Python operators handle math and logic, giving us the power to turn raw inputs into meaningful results.
Arithmetic operators
At its core, a Python program is often just a series of expressions. An expression is any combination of values and operators that evaluates to a single result. Python supports all standard mathematical operations, plus a few special ones for precise control over division and powers.
Standard math: Addition (
+), subtraction (-), and multiplication (*) work exactly as expected.Exponents: To raise a number to a power (like squaring or cubing), use the double asterisk (
**).True Division (/): Always returns a float (decimal), even if the result is a whole number (e.g.,
5 / 2is2.5).Floor Division (//): Divides and rounds down to the nearest whole integer (e.g.,
5 // 2is2).Modulo (%): Returns the remainder of the division (e.g.,
5 % 2is1). This is useful for checking if numbers are even/odd or cycling through values.
Line 3: We use multiplication (
*) to calculate the tax portion. This is the standard operator for scaling a number by a factor.Line 4: We combine addition (
+) and subtraction (-) in a single expression. This calculates the final total by adding the tax and subtracting a discount, showing how operators can be chained to model real-world transactions.Line 7: We use the exponentiation operator (
**) to perform a power calculation. Unlike multiplication, this allows for exponential growth, such as calculating the area of a square.Line 11: We apply floor division (
//) to determine the number of full units. This is the primary tool for "bucketing" data, determining how many complete 60-second cycles fit into our total count.Line 12: We use the modulo operator (
%) to capture the "remainder." This represents the leftover seconds that didn't fit into a whole minute.
Comparison operators
While arithmetic operators produce numbers, comparison operators produce Python boolean expressions that result in True or False. We use these to assert relationships between values, which is the foundation of decision-making in code.
Equality:
==(note the double equals; single=is for the assignment.Inequality:
!=(checks if values are not equal).Ordering:
<,>,<=,>=.
Line 5: We use the greater-than operator (
>) to test a specific condition. Rather than performing math, this line "asks a question" about the data. Since the relationship is valid, Python generates aTrueboolean state and binds it to the variable, creating a permanent record of that successful check. Try replacing it with<to see the updated result.Line 6: We use the greater-than-or-equal-to operator (
>=). This is a more inclusive check; it returnsTrueif the score is better than or simply meets the requirement. This is essential for setting "minimum thresholds" in logic (like a passing grade). Try replacing it with<=to see the updated result.Line 7: We apply the equality operator (
==) to check for an exact match. It is crucial to distinguish this double-equals (which compares) from the single-equals (which assigns). Even though the numbers are close, the lack of an exact match results inFalse.Lines 9–10: We output the results using f-strings. This demonstrates how complex numeric data can be simplified into a binary "Yes/No" signal that is much easier for a program to use when deciding which branch of code to execute next.
Logical operators
We often need to check multiple conditions at once. Python provides logical operators to combine boolean expressions.
and: ReturnsTrueonly if both operands are true.or: ReturnsTrueif at least one operand is true.not: Inverts the value (TruebecomesFalse, and vice versa).
Line 6: We use the
andoperator to establish a strict, cumulative requirement. This logic acts as a filter: for the final result to beTrue, every single input condition must be satisfied. Because the user has both a ticket and an ID, the logical gate opens.Line 9: We apply the
oroperator to create a flexible, "either/or" condition. This logic allows for multiple paths to success. Even though the user is not a VIP, the presence of a ticket is sufficient to satisfy the requirement, demonstrating howorprovides a fallback mechanism in programming logic.Line 12: We use the
notoperator to perform a logical inversion. This is often used to create "guard clauses" or to flip a positive state into a negative one. By applyingnottohas_access(which wasTrue), we derive a new state—is_banned—that is exactly the opposite, allowing us to define rules based on the absence of a privilege.
Operator precedence and grouping
When an expression contains multiple operators, Python does not simply evaluate them from left to right. It follows a strict order of operations, similar to the PEMDAS order in mathematics.
Precedence order (highest to lowest):
Parentheses
()Exponentiation
**Multiplication/Division
*,/,//,%Addition/Subtraction
+,-Comparison
==,>, etc.Logical
not,and,or
If we rely on default precedence, code can become buggy. We use parentheses to explicitly group operations, forcing Python to evaluate specific parts of an expression first.
Line 2: Python multiplies
5 * 2first, then adds10, resulting in20.Line 5: The parentheses force
10 + 5to be evaluated first. The result15is then multiplied by2, resulting in30.
We now possess the ability to write expressions that model real-world rules, from calculating exact averages to checking complex logical states. By mastering the full suite of arithmetic, comparison, and logical operators, and understanding how to group them with parentheses, we ensure our code behaves exactly as we intend.