Numbers and Math: Balancing the Ledger
A ledger is useless if you can't add up the totals. In Python, we use Arithmetic Operators to perform calculations. Since you already know about Integers and Floats, let's see how they interact.
The Basic Operators
Most of these look exactly like the math you learned in school:
+Addition:5 + 2is7-Subtraction:5 - 2is3*Multiplication:5 * 2is10/Division:5 / 2is2.5(Note: Division always results in a Float)
The "Special" Operators
Python has a few tools that are specific to programming:
- Floor Division (
//): Divides and chops off the decimal.5 // 2is2. - Exponent (
**): Raises a number to a power.5 ** 2is25. - Modulo (
%): Returns the remainder of a division.5 % 2is1(because 2 goes into 5 twice, with 1 left over).
Order of Operations
Python follows the standard mathematical order of operations, often remembered by the acronym PEMDAS (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction).
When in doubt, use parentheses to make your intentions clear to the computer:
🏆 The Ledger Challenge: The Interest Calculator
You are calculating the final balance of a ledger entry after a year of 5% interest.
Task:
- Create a variable
principaland set it to1000. - Create a variable
interest_rateand set it to0.05. - Create a variable
totalthat calculates the final amount using the formula: $$Total = principal + (principal \times interest_rate)$$ - Print the
total.
Bonus: Use the int() function to print only the whole number part of the total!
Write your code below:
📚 Deep Dive
Next Steps
Calculations are great, but a ledger needs to make decisions. In the next lesson, we’ll learn how to compare values using Booleans and Comparison Operators.