Combining Statements and Functions Exercise:
Define a function that determines whether the surface area of a cube is greater than its volume.
The tutorial you may need: An introduction to Python Functions
For this exercise, apart from the formulas for the surface and volume, you’ll need to know three big concepts: conditional statements, functions, and how to implement conditional statements in functions.
We start by defining a function that takes a single parameter (a) – the length of the side of the cube.
We follow that with an IF statement testing whether the volume is larger. Recall that the volume of a cube is the length of its sides to the power of three.
We can calculate that in two ways – either by using the ‘pow()’ function or the algorithmic operator ‘**’. In our specific case, the two ways of writing it out are as follows:
Now, the surface area, on the other hand, is calculated by finding the area for one face of the cube and multiplying it by 6 (for each of the 6 identical sides). Therefore, the surface area would be equal to ‘6*a**2’or ‘6*pow(a,2)’. Knowing all of this, we can write out the initial IF statement we require, and it would look like this:
if pow(a,3) > 6*a**2:
We then return the appropriate message “The volume is greater.”. Remember to indent the return command, so that it is only executed within the IF statement.
if pow(a,3) > 6*a**2: return ("The volume is greater.")
Next, we add another IF statement checking whether the surface area is greater. Knowing the proper ways to express volume and area, our IF statement would look like this:
if a**3 < 6*a**2:
Now, just as with the first IF statement, we indent and return the appropriate message.
if a**3 < 6*a**2: return ("The surface are is greater.")
By utilizing the fact that returning a value exits the function, we simply add another return statement at the end that returns a message indicating area and volume are equal. We comment a lot on that in this exercise. Make sure not to indent it under any of the prior IF statements. Reaching this line indicates that the parameter contradicts both IF statements preceding it, which makes adding any ELSE statements here unnecessary. Thus, our entire code looks like this:
def surface_or_volume(a): if pow(a,3) > 6*a**2: return ("The volume is greater.") if a**3 < 6*a**2: return ("The surface are is greater.") return ("They are equal.")
To ensure our work is accurate, call the function several times using different values for the parameters and check whether our code works as intended. Make sure to test for all possible scenarios.
That wasn’t so bad was it?
Okay, keep up the good work and check our other exercises here!