2.7 Notes — Python Math Operators

Overview of Python Math Operators

  • Python provides a set of arithmetic operators used to perform mathematical calculations in programs. Most real-world algorithms rely on such calculations, so these tools are foundational for programming.
  • A math expression is a combination of values (operands) and operators that Python evaluates to a value.
  • Example of a simple math expression: 12+2=1412 + 2 = 14

The Python Math Operators (Table references summarized)

  • + : addition — adds two numbers
  • - : subtraction — subtracts one number from another
  • * : multiplication — multiplies one number by another
  • / : floating-point division — divides and returns a floating-point result
  • // : integer (floor) division — divides and returns a whole number (integer) result
  • % : remainder (modulus) — returns the remainder after division
  • ** : exponentiation — raises a number to a power
  • Operands are the values located on the left and right of an operator.

Simple arithmetic with variables

  • Example: hours * payrate multiplies a value held in hours by the value held in payrate.
  • When you compute a value in Python, you often store it in a variable so you can reuse it.

Assignment to save results

  • An assignment statement stores the result of a computation in a variable.
  • Example program flow (conceptual):
    • salary = 2500.34
    • bonus = 1200.67
    • pay = salary + bonus
    • print("Your pay is", pay)
  • Program output example: Your pay is 3700 (based on the transcript’s numbers; actual result may differ with precise decimals).
  • Key idea: assign the result of a math expression to a variable so the value can be used again later in the program.

Working with percentages

  • When using percentages, convert to a decimal by dividing by 100 before applying arithmetic.
  • Example scenario: a 20% discount on an item.
  • Algorithm: get original price, compute discount as 20% of the original price, subtract discount from the original price, display sale price.
  • In code form:
    • original_price = float(input("Enter the item's original price: "))
    • discount = original_price * 0.2 # 20%
    • saleprice = originalprice - discount
    • print("The sale price is", sale_price)
  • Example: If the original price is 100, the sale price is 80.

Floating-point division vs integer division

  • Two division operators in Python: "/" (floating-point division) and "//" (integer division).
  • Floating-point division example: 5 / 2 = 2.5
  • Integer division example: 5 // 2 = 2
  • Behavior with negative results: integer division uses floor division semantics in Python. For example, -5 // 2 = -3 (note the floor toward negative infinity). The transcript describes a truncation behavior for positives and a rounding-away-from-zero notion for negatives; Python's actual behavior is floor division for negative results.
  • Important: understand the difference between the two operators and how they interact with sign.

Operator precedence and associativity

  • Precedence (highest to lowest) in Python:
    1) exponentiation: **
    2) multiplication, division, integer division, remainder: *, /, //, %
    3) addition, subtraction: +, -
  • Exponentiation (**): right-associative (for example, a ** b ** c is a ** (b ** c)).
  • Other operators with the same precedence are evaluated left-to-right, with an exception for exponentiation (see above).
  • Parentheses can force a particular order of evaluation.
  • Example illustrating precedence: If outcome = 12 + 6.0 / 3.0, the division is performed before the addition, yielding 14.0. Parentheses can alter the result if you want a different order of operations.

Table-based examples (referenced in the transcript)

  • Tables (e.g., Table 2-4 and Table 2-5) illustrate various expressions and their values.
  • Common simple examples to reinforce precedence:
    • 5 + 2 = 7
    • 3 * 4 = 12
    • 8 + 12 = 20
  • The tables show more complex expressions and their computed values, illustrating how Python evaluates mixed operators.

The spotlight: calculating an average

  • Average of a group of values is computed by summing them and dividing by the count.
  • Common pitfall: incorrect placement of the division can lead to wrong results.
  • Correct approach for three scores (test1, test2, test3):
    • average = (testone + testtwo + test_three) / 3.0
  • Example program (three test scores):
    • test_one = float(input("Enter the first test score: "))
    • test_two = float(input("Enter the second test score: "))
    • test_three = float(input("Enter the third test score: "))
    • average = (testone + testtwo + test_three) / 3.0
    • print("The average score is", average)
  • Example run (inputs: 90, 80, 100) yields an average of 90 in the transcript.

The exponent operator in practice

  • Exponent operator is written as **.
  • Example: area = length ** 2
  • Interactive results shown in the transcript (examples):
    • 4 ** 2 = 16
    • 5 ** 3 = 125
    • 2 ** 10 = 1024

The modulus (remainder) operator

  • The operator % returns the remainder after division.
  • Example: leftover = 17 % 3 # 17 divided by 3 leaves a remainder of 2
  • Uses: periodic calculations, time conversions, odd/even checks, etc.
  • Time conversion example (seconds to hours, minutes, seconds) using / and % and //:
    • total_seconds = float(input("Enter a number of seconds: "))
    • hours = total_seconds // 3600
    • minutes = (total_seconds // 60) % 60
    • seconds = total_seconds % 60
    • print("The time is", hours, "hours", minutes, "minutes", seconds, "seconds")
  • Example: input 11730 seconds yields 3 hours, 15 minutes, 30 seconds (per transcript).

Converting math formulas to programming statements

  • Common math formula: P = F / (1 + r) ^ n, where
    • P = present value (amount to deposit today)
    • F = future value (amount desired in the account)
    • r = annual interest rate
    • n = number of years
  • Algorithm to compute present value in code:
    • future_value = float(input("Enter the desired future value: "))
    • rate = float(input("Enter the annual interest rate: "))
    • years = int(input("Enter the number of years: "))
    • presentvalue = futurevalue / ((1 + rate) ** years)
    • print("You will need to deposit this amount:", present_value)
  • Example output (from transcript): futurevalue = 10,000; rate = 0.05; years = 10; presentvalue ≈ 6000.00 (rounded to two decimals in practice).
  • Note: In practice, dollar amounts are often rounded to two decimal places, which is covered later in the course.

Mixed-type expressions and explicit data-type conversion

  • Rule of types:
    • int op int -> int
    • float op float -> float
    • int op float or float op int -> float (promoted to float)
  • Mixed-type example (implicit promotion):
    • number = 5 + 2.0 # 7.0
    • number = 5.2 * 2.0 # 10.4
  • Explicit conversion functions:
    • int(x) converts a float to an int by truncating the fractional part (toward zero)
    • float(x) converts an int (or other types) to a float
  • Examples:
    • value = 2.6
    • i_value = int(value) # 2
    • v = -2.9
    • ivalueneg = int(v) # -2
    • i_value keeps truncation toward zero, not floor toward negative infinity
    • i_value = int(-2.9) # -2
    • f_value = float(2) # 2.0

Breaking long statements into multiple lines

  • Python supports two primary ways to split long statements:
    • Line continuation character: use a backslash at the end of the line to continue on the next line.
      Example:
    • result = barone + bartwo + barthree + \ barfour + bar_five
    • Implicit continuation inside parentheses, brackets, or braces; lines can break without a backslash inside these groupings.
      Example:
    • total = (
      valueone + valuetwo + valuethree + valuefour + value_five
      )

Non-interactive checkpoint questions (2.7 section)

  • 2.19 (conceptual): Complete the expressions by evaluating them with proper precedence:
    • Example expressions (illustrative, with correct evaluation):
    • 6 + 3 * 5 = 6 + 15 = 21
    • 12 / (11 - 4) = 12 / 7 ≈ 1.714…
    • 9 + 12 * (8 - 3) = 9 + 12 * 5 = 69
  • 2.21: Value of result for the expression Result = 9 % 2 is 1
  • 2.2 (general prompt): Determine the value of result for the given expression (depends on the exact expression shown in the transcript). The key skill is applying the correct operator precedence and associativity.

Practical takeaways and connections

  • Always consider operator precedence to predict results without running code.
  • Use parentheses to make the intended order explicit and avoid subtle bugs.
  • When mixing ints and floats, be mindful that results will typically be float values (type promotion).
  • Use line continuation or parentheses to keep code readable when expressions are long.
  • For numerical outputs (like currency), format to two decimals in real programs.

Quick reference cheat sheet

  • Basic arithmetic: a+b, ab, ab, a/b, a//b, a%b, aba + b,\ a - b,\ a * b,\ a / b,\ a // b,\ a \% b,\ a ** b
  • Present value formula in Python:
    • presentvalue = futurevalue / ((1 + rate) ** years)
  • Average of three numbers:
    • average = (a + b + c) / 3.0
  • Time conversion helper equations:
    • hours = total_seconds // 3600
    • minutes = (total_seconds // 60) % 60
    • seconds = total_seconds % 60
  • Modulus example: 17%3=217 \% 3 = 2
  • Exponent examples: 42=16, 53=125, 210=10244^2 = 16,\ 5^3 = 125,\ 2^{10} = 1024 (in Python: 42=16, 53=125, 210=10244 ** 2 = 16,\ 5 ** 3 = 125,\ 2 ** 10 = 1024)
  • Discount example (20%): discount=originalextprice×0.2, saleextprice=originalextpricediscountdiscount = original ext{-}price \times 0.2, \ sale ext{-}price = original ext{-}price - discount
  • Display example: printing a sentence with a computed value, e.g., "Your pay is" and the numeric result.