CS108
Spring 2025

Assignment 2: Functions, Parameters, and Return Values

due by 9:00 p.m. EST on Tuesday 1/28/24

Preliminaries

In your work on this assignment, make sure to abide by the collaboration policies of the course.

For each problem in this problem set, we will be writing or evaluating some Python code. You are encouraged to use the Spyder IDE which will be discussed/presented in class, but you are welcome to use another IDE if you choose.

If you have questions while working on this assignment, please post them on Piazza! This is the best way to get a quick response from your classmates and the course staff.

Programming Guidelines

  • Refer to the class Coding Standards for important style guidelines. The grader will be awarding/deducting points for writing code that comforms to these standards.

  • Every program file must begin with a descriptive header comment that includes your name, username/BU email, and a brief description of the work contained in the file.

  • Every function must include a descriptive docstring that explains what the function does and identifies/defines each of the parameters to the function.

  • Your functions must have the exact names specified below, or we won’t be able to test them. Note in particular that the case of the letters matters (all of them should be lowercase), and that some of the names include an underscore character (_).

  • Make sure that your functions return the specified value, rather than printing it. None of these functions should use a print statement.

  • If a function takes more than one input, you must keep the inputs in the order that we have specified.

  • You should not use any Python features that we have not discussed in class or read about in the textbook.

  • Your functions do not need to handle bad inputs – inputs with a type or value that doesn’t correspond to the description of the inputs provided in the problem.

  • You must test your work before you submit it You can prove to yourself whether it works correctly – or not – and make corrections before submission. If you need help testing your code, please ask the course staff!

  • Do not submit work with syntax errors. Syntax errors will cause the Gradescope autograder to fail, resulting in a grade of 0.

Warnings: Individual Work and Academic Conduct!!

  • This is an individual assignment. You may discuss the problem statement/requirements, Python syntax, test cases, and error messages with your classmates. However, each student must write their own code without copying or referring to other student’s work.

  • It is strictly forbidden to use any code that you find from online websites including but not limited to as CourseHero, Chegg, or any other sites that publish homework solutions.

  • It is strictly forbidden to use any generative AI (e.g., ChatGPT or any similar tools**) to write solutions for for any assignment.

Students who submit work that is not authentically their own individual work will earn a grade of 0 on this assignment and a reprimand from the office of the Dean.

If you have questions while working on this assignment, please post them on Piazza! This is the best way to get a quick response from your classmates and the course staff.


Task 1: Practice Writing Functions

Begin by dowloading the starter code file a02_functions.py. You will write several simple functions in this file.

  1. Write a function cube(x) that takes a number x as its input and returns the cube of its input (i.e., x raised to the power of 3). For example:

    >>> cube(2)
    8
    >>> cube(-5)
    -125
    

    Warning

    Make sure that your function returns the correct value rather than printing it. If your function is printing the return value, you will see the word None as part of the output for the second test above. If you are seeing None in your output, you must fix your function so that it uses a return statement rather than a print statement. This same warning applies to all of the functions that you will write for this assignment.

    Note: You should leave one or two blank lines between functions to make things more readable, and make sure to include a docstring like the one in our example function.

    Warning

    Make sure that you use the correct amount of indentation. In particular, your docstrings should be indented by 4 spaces as shown in our code for opposite, so that they line up with the code inside the function.

  2. Write a function slope(x1, y1, x2, y2) that takes four numeric inputs that specify the coordinates of two points (x1, y1) and (x2, y2) in the Cartesian plane, and that returns the slope of the line formed by those two points. Recall that slope is given by the following formula:

             y2 - y1
    slope = ---------
             x2 - x1
    

    Examples:

    >>> slope(2, 3, 4, 7) # line between (2,3) and (4,7)
    2.0
    >>> slope(7, 2, 3, 4) # line between (7,2) and (3,4)
    -0.5
    >>> slope(2, 3, 5, 3) # a horizontal line!
    0.0
    

Notes:

.

  1. Write a function cylinder_volume(diameter, height) that calculates and returns the volume of a cylinder of a given diameter and height.

    The volume of a cylinder is given by: v = π r^2 h.

    For example:

    >>> cylinder_volume(10,10)
    785.3975
    

    You may assume that the value of pi is 3.14159. Do not round your answer, simply return the floating point value.


Task 2: Descriptive Statistics

Begin by downloading the starter-code called a02_stats.py. In the file, you will write 4 functions to calculate and return statistical measures of a series of five numbers, specifically their sum, arithmetic mean (or average), variance, and standard deviation.

If you are not familiar with these statistical measures, you should consult Math is Fun‘s statistics webpage for a good introduction and some examples.

Have a look at the unit test code section at the bottom of the file, which is reproduced here:

# THE SECTION BELOW CONTAINS A SAMPLE OF CLIENT CODE FOR THE FUNCTIONS
if __name__ == '__main__':

    # declare variables with which to test the functions
    a = 8
    b = 9
    c = 10
    d = 9
    e = 8

    # call the `calc_sum` function to calculate the sum of these 5 variables. 
    # assign the result into a variable called `sum_of_obs`, and then print it out.
    sum_of_obs = calc_sum(a, b, c, d, e) 
    print("The sum of observations is:", sum_of_obs)

    # you need to call each of your other functions below, 
    # and verify the results by printing them out

Program Details

For each function that you write:

* you must also write one line of code to call that function, and store the 
  result in a variable, and

* another to print out the result that was returned from the function.

Test your code by running the file, and verify the results printed out in the console output window.

Greek letter Sigma (Σ)

  • In the problems that follow, you will see the greek letter sigma (Σ). This is mathematical notation for a summation of a series of values. In Python, we will accomplish this adding individual values together.

A warning

It is often tempting to try to write all of the code at once, and then move on to testing. This is a recipe for NOT being successful. The most successful approach is to write a small (one or two lines of code)), and then test it to prove to yourself that it is correct.

Get into the habit of writing one function and testing it thoroughly before moving on to another function.

  1. Write the function calc_sum(a, b, c, d, e) to calculate and return the sum of the 5 parameters (i.e., a + b + c + d + e).

  2. Write the function calc_mean(a, b, c, d, e) to calculate and return the mean (arithmetic average) of the 5 parameters. The mean (represented by the Greek letter mu) is given by:

    The capital letter Sigma is the summation operator, meaning we are adding up a series of values – the values in the variables a, b, c, d, and e. Then we divide this sum by N (the number of values).

    Note:

    Avoid code duplication! You should call your calc_sum function from within calc_mean, and save the result in a local variable for use within this function.

  3. Write the function calc_variance(a, b, c, d, e) to calculate and return the variance (a measure of the distribution) of the 5 parameters.

    The variance is a measure of the dispersion of observations around their mean. Specifically, the variance is the average squared deviation* from the mean.

    Calculating the variance is a multi-step process, so you should break it into several lines of code. First, you will need to obtain the mean of the parameters – call your function calc_mean and store the result in a local variable.

    The variance (represented by the Greek letter (lowercase) sigma squared) is given by:

    The capital letter Sigma is the summation operator, meaning we are adding up a series of terms – the square of each value minus its mean. This sum is called the sum of squares, and with 5 parameters we can write the sum of squares as:

    Once we have the sum of squares, we can compute the average sum of squares, by dividing it by N (the number of values).

    Note:

    Avoid code duplication! You should call your calc_mean function from within calc_variance, and save the result in a local variable for use within this function.

  4. Write the function calc_stdev(a, b, c, d, e) to calculate and return the standard deviation (a measure of the distribution) of the 5 parameters. The standard deviation (represented by the Greek letter sigma) is the square root of the variance.

    Note:
    Avoid code duplication! You should call your calc_variance function from within calc_stdev, and save the result in a local variable for use within this function.


Submitting Your Work

20 points; will be assigned by code review

Log in to GradeScope to submit your work.

Be sure to name your files correctly!

Under the heading for Assignment 2, attach each of the 2 required files to your submission.

When you upload the files, the autograder will test your functions/programs.

Warning: Beware of Global print statements

  • The autograder script cannot handle print statements in the global scope, and their inclusion causes this error:

autograder_fail

*   Why does this happen? When the autograder imports your file, the `print` 
    statement(s) execute (at import time), which causes this error.

*   You can prevent this error by not having any `print` statements in the global scope.
    Instead, create an `if __name__ == '__main__':` section at the bottom of the file, and
    put any test cases/print statements in that controlled block. For example:

        if __name__ == '__main__':

            ## put test cases here:
            print('fv_lump_sum(0.05, 2, 100)', fv_lump_sum(0.05, 2, 100))

*   `print` statements inside of functions do not cause this problem.

Notes: