Writing Functions - Exercises - SOLVED
Contents
Writing Functions - Exercises - SOLVED#
Walkthrough example#
Write a function that takes a single input value, \(x\) and returns that number cubed \(x^3\). The function should be called cube.
If you think you know how to do this, or how to do parts of this, please go ahead. If not, or if you need hints on parts of this, please read through the steps below.
Step 1: Add a
defline. All functions begin with adefline. This provides two things: The name of the function, the input parameters to the function. So write a line that looks something likedef cube(x):Thedefsays that this is a function, thecubeis the name of the function,xis the one input parameter. Don’t forget the:, which is used to indicate that the function will now start and the next line will be indented.Step 2: Add the docstring. Add another line explaining what the function will do. This step is optional but helps to document your code. So something like
"""Cube a number""". If you need more space, write this over more than one line (that’s why we use triple quotes here).Step 3: Add the function body. This is the bulk of writing a function, and as we get further in the course the function bodies will get larger and more complex. In this case we just need to assign a new variable to store \(x^3\). So add something like
y = x**3. Remember indentation here. The body (and docstring) of a function should be indented. So this should actually bey = x**3. 4 spaces (one level of indentation) and then the code.Step 4: Add the return statement. Most (but not all) functions will have a
returnstatement (functions will have an implicitreturn Noneif you don’t write areturn, or the function never reaches areturnstatement). In this case we want toreturnthe value of \(x^3\) that we have computed and stored iny. So we would doreturn y(remembering indentation again).
Please ask us if you are not clear on any of this!
def cube(x):
"""Return the cube of x"""
y = x**3
return y
cube(4)
64
Testing your function.#
Run the cell below to test your function. It will print “Your function works” if your function works, and raise an error if it doesn’t. If it doesn’t work, see if you can figure out what is wrong. If you can’t, talk to us!
# I'll use comments to explain how this test works.
bbb = cube(4) # Call the function with an input value of 4
assert (bbb == 64) # I'm now checking that bbb is equal to 4**4 = 256. If it isn't the code will fail.
# Note that I'm using the comparison operator == from last week. assert is new. This is
# another built-in function. It raises an error the input value is False, otherwise it does
# nothing.
bbb2 = cube(-3)
assert (bbb2 == -27)
bbb3 = cube(11)
assert(bbb3 == 1331)
print("Your function works, well done!")
Your function works, well done!
Calling the function yourself.#
Finally, call your cube function to figure out what \(6.78^3\) is equal to.
cube(6.78)
311.66575200000005
Final note#
You have now written your first function. Well done!
I do note that using a function to compute \(x^3\) is probably overkill. You could just type x**3 directly. However, as we work on more complex examples functions will save us having to write the same block of code repeatedly.
Exercise#
Write a function that takes one input x and returns x**4. HINT this should look very similar to the case above!
def quartic(x):
"""Return the quartic of x"""
y = x**4
return y
# Run this cell to test if your function above works. Change the first line to match the name of your function
fn_handle = quartic
bbb = fn_handle(4) # Call the function with an input value of 4
assert (bbb == 256) # I'm now checking that bbb is equal to 4**4 = 256. If it isn't the code will fail.
# Note that I'm using the comparison operator == from last week. assert is new. This is
# another built-in function. It raises an error the input value is False, otherwise it does
# nothing.
bbb2 = fn_handle(-3)
assert (bbb2 == 81)
bbb3 = fn_handle(11)
assert(bbb3 == 14641)
print("Congratulations, it looks like your function works!")
Congratulations, it looks like your function works!
Exercise#
Write a function that takes one input x and returns \(x^5 - \frac{x^2}{24.1} + \sqrt{x}\)
def exercise3(x):
"""Return weird math function x**5 - x**2/24.1 + x**0.5"""
return x**5 - x**2/24.1 + x**0.5
# Run this cell to test if your function above works. Change the first line to match the name of your function
fn_handle = exercise3
bbb = fn_handle(4) # Call the function with an input value of 4
assert (bbb > 1025.336099 and bbb < 1025.336100) # This is a float value, so check approximate value
bbb2 = fn_handle(-3)
# This one is complex, so more involved checking needed.
assert (bbb2.real > -243.3735 and bbb2.real < -243.3734 and bbb2.imag > 1.732050 and bbb2.imag < 1.732051)
bbb3 = fn_handle(11)
assert(bbb3 > 161049.29 and bbb3 < 161049.30)
print("Congratulations, it looks like your function works!")
Congratulations, it looks like your function works!