Introduction to Python Programming

Andrew J. Pounds, Ph.D.

🔢 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.

What You'll Learn:
  • 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!

P Parentheses — Operations inside parentheses are done first
E Exponents — Powers are calculated next (using **)
M Multiplication — Multiplication operations (using *)
D Division — Division operations (using /)
A Addition — Addition operations (using +)
S Subtraction — Subtraction operations (using -)

Example 1: Simple PEMDAS

To calculate 2² + 3² you would type:

2**2 + 3**2
13

Why? 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))
-27

Let's trace through this step by step:

  1. Innermost parentheses first: 4² = 16
  2. Then: 3 - 16 = -13
  3. Then: 2² = 4
  4. Then: 4 + (-13) = -9
  5. Finally: 3 × (-9) = -27
💡 Pro Tip: Unlike math notation, you cannot write 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: 1
Why Does This Matter?

Integer 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
2

Let'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
💡 Practical Uses of Modulus:
  • Check if a number is even or odd: number % 2 is 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")
Enter a number: 7
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 math

Using 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.0
Why math. 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

⚠️ Important: All trigonometric functions in Python use radians, not degrees! If you have an angle in degrees, convert it first using 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))
Enter the radius of the circle: 5

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))
Enter an angle in degrees: 30

For 30.0 degrees:
sin = 0.49999999999999994
cos = 0.8660254037844387
💡 Note: The sine of 30° should be exactly 0.5, but we get 0.49999999999999994 due to floating-point precision limitations. This is normal in computer arithmetic!

⚠️ Common Mistakes (And How to Fix Them)

Mistake 1: Forgetting to Import Math

❌ Wrong:
x = sqrt(16) # ERROR! Python doesn't know what sqrt is
✅ Correct:
import math
x = math.sqrt(16) # Works!

Mistake 2: Missing the Multiplication Operator

❌ Wrong:
result = 3(4 + 5) # ERROR! Python thinks you're calling a function
✅ Correct:
result = 3 * (4 + 5) # You must include the * operator

Mistake 3: Using Degrees Instead of Radians

❌ Wrong:
import math
result = math.sin(90) # Wrong! This calculates sin(90 radians), not 90 degrees
✅ Correct:
import math
result = math.sin(math.radians(90)) # Converts 90° to radians first

Mistake 4: Using ^ for Exponents

❌ Wrong:
result = 2^3 # ERROR! ^ is bitwise XOR in Python, not exponent
✅ Correct:
result = 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:

  1. Asks for the lengths of two sides of a right triangle (a and b)
  2. Calculates the hypotenuse using c = √(a² + b²)
  3. Displays the result

Hint: Use math.sqrt() and the ** operator

Exercise 2: Time Converter

Write a program that:

  1. Asks for a number of seconds (as an integer)
  2. Calculates the equivalent hours, minutes, and remaining seconds
  3. 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:

  1. Asks for two integers
  2. Checks if the first number is evenly divisible by the second
  3. If so, prints "X is divisible by Y"
  4. 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:

  1. Asks for the values of a, b, and c
  2. Calculates the discriminant: b² - 4ac
  3. If the discriminant is non-negative, calculates both solutions using:
    x = (-b ± √(b² - 4ac)) / 2a
  4. 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:

  1. Asks for the lengths of two sides (a and b)
  2. Asks for the angle between them (in degrees)
  3. Calculates the area using: Area = ½ × a × b × sin(angle)
  4. Displays the result

Hint: Remember to convert degrees to radians!

Exercise 6: Compound Interest Calculator

Write a program that calculates compound interest:

  1. Asks for the principal amount (P)
  2. Asks for the annual interest rate as a percentage (r)
  3. Asks for the number of times interest is compounded per year (n)
  4. Asks for the number of years (t)
  5. Calculates the final amount using: A = P(1 + r/n)^(nt)
  6. Displays the final amount and the interest earned

📋 Quick Reference

Addition:
5 + 3 # Result: 8
Subtraction:
5 - 3 # Result: 2
Multiplication:
5 * 3 # Result: 15
Division:
5 / 3 # Result: 1.6667
Integer Division:
5 // 3 # Result: 1
Modulus (Remainder):
5 % 3 # Result: 2
Exponent:
5 ** 3 # Result: 125
Square Root:
math.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 math for 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:

  1. Read the error message—Python usually tells you what line has the problem
  2. Check your operators—did you use ** for exponents and * for multiplication?
  3. Check your imports—did you include import math at the top?
  4. Check the math. prefix—did you write math.sqrt() or just sqrt()?
  5. Check your parentheses—every ( needs a matching )
Remember: Mathematical programming takes practice. Work through the examples step by step, and don't be afraid to experiment with different values to see how the operators behave!