🧮 Crunching the Numbers
Welcome to Module 2! Numbers are fundamental in AI – from counting data points to calculating probabilities, adjusting model parameters, and measuring performance. Python makes working with numbers intuitive.
We'll explore Python's built-in math tools (operators) and learn how it decides which calculation to do first (precedence). This is key for writing correct algorithms!
🛠️ Python's Math Toolkit
These symbols perform basic math operations.
Addition (+)
Adds two numbers. Example: 5 + 3
results in 8
.
Subtraction (-)
Subtracts the second number from the first. Example: 10 - 4
results in 6
.
Multiplication (*)
Multiplies two numbers. Example: 6 * 7
results in 42
.
Division (/)
Divides the first number by the second. Always results in a float. Example: 10 / 4
results in 2.5
.
Floor Division (//)
Divides and rounds down to the nearest whole number (integer). Example: 10 // 4
results in 2
.
Modulo (%)
Gives the remainder of a division. Example: 10 % 3
results in 1
(10 divided by 3 is 3 with a remainder of 1).
Exponentiation (**)
Raises the first number to the power of the second. Example: 2 ** 3
results in 8
(2 * 2 * 2).
🚦 Order Matters: Operator Precedence
Python follows rules to decide the calculation order (like PEMDAS/BODMAS).
-
1
Parentheses
( )Anything inside parentheses is calculated first.
-
2
Exponentiation
**Calculated next.
-
3
Multiplication, Division, Floor Div, Modulo
* / // %Calculated from left to right.
-
4
Addition, Subtraction
+ -Calculated last, from left to right.
Understanding precedence is vital for correct calculations in your algorithms!
⚙️ Math in Action: Following the Order
Let's see how Python evaluates an expression using precedence rules.
How does Python solve this? It follows the precedence rules:
- First, **Highest precedence after parentheses. (Exponentiation): `2 ** 2` becomes `4`.
- Next, * Multiplication and Floor Division have same precedence, done left-to-right. (Multiplication): `5 * 4` becomes `20`.
- Then, //Floor division is next in the left-to-right sequence. (Floor Division): `20 // 3` becomes `6` (rounds down).
- Now, + Addition and Subtraction have the lowest precedence, done left-to-right. (Addition): `10 + 6` becomes `16`.
- Finally, - Subtraction is the last operation. (Subtraction): `16 - 1` results in `15`.
So, the variable `result` will store the value 15.
🧠 Quick Check!
Module 2 Theory Complete!
Great calculation! You now know Python's arithmetic operators and how precedence guides calculations. This forms the basis for many AI algorithms.
Time to practice! Head to the Practice Zone or the Advanced Practice for Module 2.