Python Code Example: volume and surface area of a ball

This code calculates the volume and surface area of a sphere with a given radius. The user is prompted to input the radius, which is then passed as an argument to two functions getVolume and getSurfaceArea.

getVolume calculates the volume of the sphere using the formula:

((4 * math.pi * r^3) / 3)

where r is the radius and math.pi is the constant pi from the math module.

getSurfaceArea calculates the surface area of the sphere using the formula:

4 * math.pi * r^2

The truncate function is used to round the volume and surface area to 2 decimal places.

Finally, the returned values from the functions are printed with the strings “Volume: ” and “Surface: “. The repr function is used to convert the numbers to strings so they can be concatenated with the strings.

import math

def getVolume(r):
    return ((4 * math.pi * pow(r, 3)) / 3)

def getSurfaceArea(r):
    return 4 * math.pi * pow(r, 2)

def truncate(n, d=0):
    m = 10 ** d
    return int(n * m) / m

radius = int(input("Please enter radius: "))
volume = truncate(getVolume(radius), 2)
area = truncate(getSurfaceArea(radius), 2)

print("Volume: " + repr(volume))
print("Surface: " + repr(area))
Please enter radius: 4
Volume: 268.08
Surface: 201.06