Search⌘ K
AI Features

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 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 / 2 is 2.5).

  • Floor Division (//): Divides and rounds down to the nearest whole integer (e.g., 5 // 2 is 2).

  • Modulo (%): Returns the remainder of the division (e.g., 5 % 2 is 1). This is useful for checking if numbers are even/odd or cycling through values.

Python
# 1. Standard Math & Exponents
price = 100
tax = price * 0.20 # Multiplication
total = price + tax - 5 # Addition & Subtraction
side = 4
area = side ** 2 # Exponent: 4 squared is 16
# 2. The Three Divisions
total_seconds = 130
minutes = total_seconds // 60 # Floor: 2 whole minutes
seconds = total_seconds % 60 # Modulo: 10 remaining seconds
precise = total_seconds / 60 # True: 2.166...
print(f"Total Cost: {total}")
print(f"Time: {minutes} min, {seconds} sec")
  • 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: <, >, <=, >=.

Python
current_score = 105
high_score = 100
# Check relationships
is_new_record = current_score > high_score # True
is_qualifying = current_score >= 100 # True (Greater or Equal)
is_exact_tie = current_score == high_score # False
print(f"New Record: {is_new_record}")
print(f"Qualified: {is_qualifying}")
  • 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 a True boolean 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 returns True if 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 in False.

  • 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: Returns True only if both operands are true.

  • or: Returns True if at least one operand is true.

  • not: Inverts the value (True becomes False, and vice versa).

Python 3.14.0
has_ticket = True
is_vip = False
has_id = True
# AND: Both must be true
can_enter = has_ticket and has_id
# OR: Only one needs to be true
has_access = is_vip or has_ticket
# NOT: Inverts the state
is_banned = not has_access
print(f"Can Enter: {can_enter}")
print(f"Has Access: {has_access}")
  • Line 6: We use the and operator to establish a strict, cumulative requirement. This logic acts as a filter: for the final result to be True, 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 or operator 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 how or provides a fallback mechanism in programming logic.

  • Line 12: We use the not operator to perform a logical inversion. This is often used to create "guard clauses" or to flip a positive state into a negative one. By applying not to has_access (which was True), 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):

  1. Parentheses ()

  2. Exponentiation **

  3. Multiplication/Division *, /, //, %

  4. Addition/Subtraction +, -

  5. Comparison ==, >, etc.

  6. 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.

Python
# Default: Multiplication (*) happens before Addition (+)
result_default = 10 + 5 * 2 # 10 + 10 = 20
# Grouped: Parentheses force Addition (+) first
result_grouped = (10 + 5) * 2 # 15 * 2 = 30
print(f"Default: {result_default}")
print(f"Grouped: {result_grouped}")
  • Line 2: Python multiplies 5 * 2 first, then adds 10, resulting in 20.

  • Line 5: The parentheses force 10 + 5 to be evaluated first. The result 15 is then multiplied by 2, resulting in 30.

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.