Worked Examples: Using Python as a Calculator#

These worked solutions correspond to the exercises on the Using Python as a Calculator page.

How to use this notebook:

  • Try each exercise yourself first before looking at the solution

  • The code cells show both the code and its output

  • Download this notebook if you want to run and experiment with the code yourself

  • Your solution might look different - that’s fine as long as it gives the correct answer!

Setup#

We’ll import the math module once here at the beginning. In a Jupyter notebook, once you import a module in a cell and run that cell, the module remains available for all subsequent cells in the same session.

import math

Exercise 1: Volume of a Sphere#

Problem: Calculate the volume of a sphere with a radius of 5 units. Use math.pi and the formula

(5)#\[\begin{equation} V = \frac{4}{3} \pi r^3 \end{equation}\]

Solution:

import math

(4 / 3) * math.pi * 5**3
523.5987755982989

Explanation:

  • We use math.pi to get the value of \(\pi\)

  • The radius is 5, so we calculate \(r^3\) using 5**3

  • We calculate \(\frac{4}{3}\) using 4 / 3 (which gives a float: 1.333…)

  • Following the order of operations (BODMAS), this evaluates to approximately 523.60 cubic units

Key concept: Python’s ** operator is used for exponentiation (raising to a power).

Exercise 2: Degrees to Radians#

Problem: Convert 45 degrees to radians using math.radians().

Solution:

import math

math.radians(45)
0.7853981633974483

Explanation:

  • The math.radians() function converts degrees to radians

  • We pass 45 as the argument to convert 45°

  • The result is approximately 0.7854 radians, which equals \(\frac{\pi}{4}\)

Why radians matter: Python’s trigonometric functions expect angles in radians, not degrees.

Verification: We can check that this equals π/4:

import math

math.pi / 4
0.7853981633974483

They match!

Exercise 3: Logarithm Base 2#

Problem: Calculate log base 2 of 32 using math.log(x, base).

Solution:

import math

math.log(32, 2)
5.0

Explanation:

  • math.log(x, base) calculates the logarithm of the first argument with the specified base

  • We’re finding \(\log_2(32)\), which asks: “2 to what power equals 32?”

  • The answer is 5.0 because \(2^5 = 32\)

Verification: Let’s confirm that \(2^5 = 32\):

2**5
32

Note: If you don’t specify a base, math.log(x) calculates the natural logarithm (base \(e\)). If you want \(\log_{10}\) you can use math.log10.

import math

math.log(32)  # This is ln(32), not log₂(32)
3.4657359027997265