Page5/20
Variables & Data Types Β· Page 5 of 5
Math Operations
Arithmetic Operators
Python can do all basic math. These are your building blocks for data calculations.
| Operator | Symbol | Example | Result |
|---|---|---|---|
| Addition | + | 10 + 3 | 13 |
| Subtraction | - | 10 - 3 | 7 |
| Multiplication | * | 10 * 3 | 30 |
| Division | / | 10 / 3 | 3.333... |
| Floor Division | // | 10 // 3 | 3 |
| Modulo (Remainder) | % | 10 % 3 | 1 |
| Power/Exponent | ** | 2 ** 8 | 256 |
Division vs Floor Division (Important!)
10 / 3 # 3.3333... β Regular division (always float)
10 // 3 # 3 β Floor division (rounds down to integer)
10 % 3 # 1 β Remainder (10 = 3*3 + 1)
Real example: Converting minutes to hours and minutes
total_minutes = 125
hours = total_minutes // 60 # 2 hours
remaining_minutes = total_minutes % 60 # 5 minutes
print(f"125 minutes = {hours}h {remaining_minutes}m") # 2h 5m
Order of Operations (PEMDAS)
Python follows the standard math order:
- P β Parentheses first
- E β Exponents
- MD β Multiplication & Division (left to right)
- AS β Addition & Subtraction (left to right)
2 + 3 * 4 # 14 (not 20!)
(2 + 3) * 4 # 20
10 - 3 - 2 # 5 (left to right: (10-3)-2)
2 ** 3 ** 2 # 512 (right to left: 2**(3**2) = 2**9)
The math Module
For advanced math, import Python's built-in math module:
import math
math.sqrt(16) # 4.0
math.pi # 3.14159265...
math.ceil(4.2) # 5 (round up)
math.floor(4.8) # 4 (round down)
math.abs(-5) # 5 (absolute value)
math.log(100, 10) # 2.0 (logarithm)
Variable Assignment Shortcuts
Python provides shortcuts for updating variables:
score = 0
score = score + 10 # Traditional
score += 10 # Shortcut (cleaner!)
# Works for all operators:
score -= 5 # score = score - 5
score *= 2 # score = score * 2
score /= 10 # score = score / 10
main.py
Loading...
OUTPUT
βΆClick "Run Code" to executeβ¦