Expressions and Operators
Arithmetic Expressions
Part of: Variables, Lists & Procedures
Variables store values, but the real work of a program happens when you combine those values. An expression is any piece of code that evaluates to a single value: 3 + 4, price quantity, or total / count are all expressions. The pieces that combine values are operators . Arithmetic operators. Python gives you the math operators you expect, plus two that trip up beginners: Two operators do the heavy lifting in countless algorithms: - // integer division drops the fractional part: 17 // 5 is 3. - % modulo gives the remainder: 17 % 5 is 2. Modulo answers "is this even?" (n % 2 == 0), "every 3rd item?" (i % 3 == 0), and "what digit?". Order of operations. Expressions follow precedence rules, just like math class: , /, //, % happen before + and -. Use parentheses to force the order you want: When unsure, add parentheses : they cost nothing and make intent clear. Building useful values. A classic pattern: split a total amount into whole units and a remainder. What usually goes wrong. What you see What caused it How to fix it --- --- --- The whole-unit answer shows a decimal, like 2.87 / was used, and true division always produces a floating-point result Use // when you want the whole part
Challenge: Cents to Dollars