🔢 Exercise Three: Mathematical Operations
Python is a really powerful language for doing mathematics. However, to quote Spider-Man, "With great power comes great responsibility." In this exercise, we'll cover the essential rules you must know to perform calculations correctly.
- How Python follows the order of operations (PEMDAS)
- The difference between integer division and regular division
- How to use the modulus (remainder) operator
- How to access trigonometric and other mathematical functions
📐 1. Order of Operations (PEMDAS)
Just like in your math classes, Python follows the standard order of operations. If you remember PEMDAS, you're already ahead!
**)
*)
/)
+)
-)
Example 1: Simple PEMDAS
To calculate 2² + 3² you would type:
2**2 + 3**2Why? Python first calculates 2² = 4 and 3² = 9, then adds them: 4 + 9 = 13
Example 2: Using Parentheses
To calculate 3(2² + (3 - 4²)) you would type:
3 * (2**2 + (3 - 4**2))Let's trace through this step by step:
- Innermost parentheses first: 4² = 16
- Then: 3 - 16 = -13
- Then: 2² = 4
- Then: 4 + (-13) = -9
- Finally: 3 × (-9) = -27
3(2+5) in Python. You must explicitly include the multiplication operator: 3 * (2+5)
⚡ Python Math Operators
| Operator | Operation | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 5 - 3 |
2 |
* |
Multiplication | 5 * 3 |
15 |
/ |
Division | 5 / 3 |
1.6667 |
** |
Exponent (Power) | 5 ** 3 |
125 |
// |
Integer Division (Floor) | 5 // 3 |
1 |
% |
Modulus (Remainder) | 5 % 3 |
2 |
➗ 2. Integer Division and Remainders
Understanding Integer Division
Python provides two types of division:
| Type | Operator | What It Does | Example |
|---|---|---|---|
| Regular Division | / |
Returns a decimal (float) result | 7 / 2 → 3.5 |
| Integer Division | // |
Returns only the whole number part (rounds down) | 7 // 2 → 3 |
# Regular division gives decimal results
print(7 / 2) # Output: 3.5
print(3 / 2) # Output: 1.5
# Integer division gives whole number results
print(7 // 2) # Output: 3
print(3 // 2) # Output: 1Integer operations are used extensively in computer science because they take less memory than floating-point numbers and are faster to calculate. They're also useful when you need whole numbers—like counting items, array indices, or distributing things evenly.
The Modulus (Remainder) Operator
The modulus operator (%) gives you the remainder after division. This is incredibly useful in programming!
>>> 8 % 3
2
>>> 8 % 4
0
>>> 17 % 5
2Let's understand what's happening:
| Expression | Division | Remainder | Explanation |
|---|---|---|---|
8 % 3 |
8 ÷ 3 = 2 | 2 | 3 goes into 8 twice (6), with 2 left over |
8 % 4 |
8 ÷ 4 = 2 | 0 | 4 goes into 8 exactly twice, no remainder |
17 % 5 |
17 ÷ 5 = 3 | 2 | 5 goes into 17 three times (15), with 2 left over |
- Check if a number is even or odd:
number % 2is 0 for even numbers - Check if a number is divisible by another: If
a % b == 0, then a is divisible by b - Get the last digit of a number:
number % 10 - Wrap around values: Keep numbers in a range (useful for games, clocks, etc.)
Example: Even or Odd Checker
# Check if a number is even or odd
number = int(input("Enter a number: "))
remainder = number % 2
if remainder == 0:
print(str(number) + " is even")
else:
print(str(number) + " is odd")7 is odd
📚 3. The Math Library
Python has a rich library of trigonometric, transcendental, and special mathematical functions. It also includes important mathematical constants. To access these, you must include this statement at the top of your program:
import mathUsing the Math Library
Once you've imported the math library, you access its functions and constants by putting math. in front of them:
import math
# Using pi
print(math.pi) # Output: 3.141592653589793
# Using cosine
print(math.cos(math.pi)) # Output: -1.0
# Using square root
print(math.sqrt(16)) # Output: 4.0math. Before Everything?
The math. prefix tells Python that you're using a function FROM THE LIBRARY. This prevents confusion if you happen to create your own variable named pi or a function named sqrt.
Common Math Functions
| Function | Description | Example | Result |
|---|---|---|---|
math.sqrt(x) |
Square root of x | math.sqrt(25) |
5.0 |
math.pow(x, y) |
x raised to power y | math.pow(2, 3) |
8.0 |
abs(x) |
Absolute value of x | abs(-5) |
5 |
math.floor(x) |
Round down to nearest integer | math.floor(3.7) |
3 |
math.ceil(x) |
Round up to nearest integer | math.ceil(3.2) |
4 |
math.log(x) |
Natural logarithm of x | math.log(math.e) |
1.0 |
math.log10(x) |
Base-10 logarithm of x | math.log10(100) |
2.0 |
math.exp(x) |
e raised to power x | math.exp(1) |
2.718... |
Trigonometric Functions
math.radians().
| Function | Description | Example | Result |
|---|---|---|---|
math.sin(x) |
Sine of x (in radians) | math.sin(math.pi/2) |
1.0 |
math.cos(x) |
Cosine of x (in radians) | math.cos(0) |
1.0 |
math.tan(x) |
Tangent of x (in radians) | math.tan(math.pi/4) |
1.0 |
math.radians(x) |
Convert degrees to radians | math.radians(180) |
3.14159... |
math.degrees(x) |
Convert radians to degrees | math.degrees(math.pi) |
180.0 |
Mathematical Constants
| Constant | Description | Value |
|---|---|---|
math.pi |
Pi (π) | 3.141592653589793 |
math.e |
Euler's number (e) | 2.718281828459045 |
math.tau |
Tau (τ = 2π) | 6.283185307179586 |
math.inf |
Positive infinity | inf |
Example: Circle Calculator
import math
# Calculate properties of a circle
radius = float(input("Enter the radius of the circle: "))
# Calculate circumference: C = 2πr
circumference = 2 * math.pi * radius
# Calculate area: A = πr²
area = math.pi * radius**2
print()
print("Circle with radius " + str(radius) + ":")
print("Circumference = " + str(circumference))
print("Area = " + str(area))Circle with radius 5.0:
Circumference = 31.41592653589793
Area = 78.53981633974483
Example: Trigonometry with Degrees
import math
# Calculate sine of an angle in degrees
angle_degrees = float(input("Enter an angle in degrees: "))
# Convert to radians first!
angle_radians = math.radians(angle_degrees)
# Now calculate the trig functions
sine_value = math.sin(angle_radians)
cosine_value = math.cos(angle_radians)
print()
print("For " + str(angle_degrees) + " degrees:")
print("sin = " + str(sine_value))
print("cos = " + str(cosine_value))For 30.0 degrees:
sin = 0.49999999999999994
cos = 0.8660254037844387
⚠️ Common Mistakes (And How to Fix Them)
Mistake 1: Forgetting to Import Math
x = sqrt(16) # ERROR! Python doesn't know what sqrt isimport math
x = math.sqrt(16) # Works!Mistake 2: Missing the Multiplication Operator
result = 3(4 + 5) # ERROR! Python thinks you're calling a functionresult = 3 * (4 + 5) # You must include the * operatorMistake 3: Using Degrees Instead of Radians
import math
result = math.sin(90) # Wrong! This calculates sin(90 radians), not 90 degreesimport math
result = math.sin(math.radians(90)) # Converts 90° to radians firstMistake 4: Using ^ for Exponents
result = 2^3 # ERROR! ^ is bitwise XOR in Python, not exponentresult = 2**3 # Use ** for exponents💪 Practice Exercises
Try writing these programs on your own! This is the best way to learn.
Exercise 1: Pythagorean Theorem
Write a program that:
- Asks for the lengths of two sides of a right triangle (a and b)
- Calculates the hypotenuse using c = √(a² + b²)
- Displays the result
Hint: Use math.sqrt() and the ** operator
Exercise 2: Time Converter
Write a program that:
- Asks for a number of seconds (as an integer)
- Calculates the equivalent hours, minutes, and remaining seconds
- Displays the result
Hint: Use integer division (//) and modulus (%)
Example: 3665 seconds = 1 hour, 1 minute, 5 seconds
Exercise 3: Divisibility Checker
Write a program that:
- Asks for two integers
- Checks if the first number is evenly divisible by the second
- If so, prints "X is divisible by Y"
- If not, prints "X is not divisible by Y, remainder is Z"
Hint: Use the modulus operator (%)
Exercise 4: Quadratic Formula
Write a program that solves ax² + bx + c = 0:
- Asks for the values of a, b, and c
- Calculates the discriminant: b² - 4ac
- If the discriminant is non-negative, calculates both solutions using:
x = (-b ± √(b² - 4ac)) / 2a - Displays the solutions
Hint: Use math.sqrt() for the square root
Exercise 5: Triangle Area (Using Trigonometry)
Write a program that calculates the area of a triangle given two sides and the included angle:
- Asks for the lengths of two sides (a and b)
- Asks for the angle between them (in degrees)
- Calculates the area using: Area = ½ × a × b × sin(angle)
- Displays the result
Hint: Remember to convert degrees to radians!
Exercise 6: Compound Interest Calculator
Write a program that calculates compound interest:
- Asks for the principal amount (P)
- Asks for the annual interest rate as a percentage (r)
- Asks for the number of times interest is compounded per year (n)
- Asks for the number of years (t)
- Calculates the final amount using: A = P(1 + r/n)^(nt)
- Displays the final amount and the interest earned
📋 Quick Reference
5 + 3 # Result: 85 - 3 # Result: 25 * 3 # Result: 155 / 3 # Result: 1.66675 // 3 # Result: 15 % 3 # Result: 25 ** 3 # Result: 125math.sqrt(25) # Result: 5.0⭐ Key Takeaways
- ✓ Python follows PEMDAS order of operations
- ✓ Use
**for exponents, not^ - ✓ You must explicitly write the
*operator for multiplication - ✓ Use
/for regular division (returns decimal) - ✓ Use
//for integer division (returns whole number) - ✓ Use
%for modulus (returns remainder) - ✓ Import the math library with
import mathfor advanced functions - ✓ Always prefix math functions with
math. - ✓ Trigonometric functions use radians—convert with
math.radians()
🚑 Need Help?
If your program doesn't work, follow these steps:
- Read the error message—Python usually tells you what line has the problem
- Check your operators—did you use
**for exponents and*for multiplication? - Check your imports—did you include
import mathat the top? - Check the
math.prefix—did you writemath.sqrt()or justsqrt()? - Check your parentheses—every
(needs a matching)