Skip to content

Homework 4: Functions

Objectives

The goal of this assignment is to gain experience working with:

  • Writing and calling functions
  • Using parameters, arguments, and return values
  • Writing docstrings with correct data types and formatting
  • Completing function stubs according to provided docstrings

Function Docstrings

For this homework, your programs must include correct documentation. Please read the Docstring Requirements for Functions carefully to see how arguments and return values should be documented.

Exercise 4.1 Children's Songs

Children's songs and nursery rhymes often include patterns and repetition. The goal of this exercise is to write Python programs that can generate the lyrics of children's songs without explicitly including the full text of the song in the code. Instead, we will take advantage of functions to combine a sequence of statements that can be executed over and over again.

As a starting point, download rhody.py. When this starter code is executed, you should see the following output:

Go tell Aunt Rhody Go tell Aunt Rhody Go tell Aunt Rhody The old gray goose is dead The one she's been saving The one she's been saving The one she's been saving To make a feather bed

Finish this program so that it prints the entire song, exactly as follows:

Go tell Aunt Rhody Go tell Aunt Rhody Go tell Aunt Rhody The old gray goose is dead The one she's been saving The one she's been saving The one she's been saving To make a feather bed The goslings are mourning The goslings are mourning The goslings are mourning Because their mother's dead The old gander's weeping The old gander's weeping The old gander's weeping Because his wife is dead She died in the mill pond She died in the mill pond She died in the mill pond From standing on her head Go tell Aunt Rhody Go tell Aunt Rhody Go tell Aunt Rhody The old gray goose is dead

Once rhody.py is working correctly, create a new program named happy.py that generates exactly the the output below. Your code should include as little repetition as possible.

If you're happy and you know it, clap your hands If you're happy and you know it, clap your hands If you're happy and you know it, and you really want to show it If you're happy and you know it, clap your hands If you're happy and you know it, slap your knees If you're happy and you know it, slap your knees If you're happy and you know it, and you really want to show it If you're happy and you know it, slap your knees If you're happy and you know it, turn around If you're happy and you know it, turn around If you're happy and you know it, and you really want to show it If you're happy and you know it, turn around If you're happy and you know it, pat your head If you're happy and you know it, pat your head If you're happy and you know it, and you really want to show it If you're happy and you know it, pat your head If you're happy and you know it, do all four If you're happy and you know it, do all four If you're happy and you know it, and you really want to show it If you're happy and you know it, do all four

Submit both rhody.py and happy.py (at the same time) to Gradescope.

Exercise 4.2 Unit Conversions

When solving physics problems, you often need to convert from one unit to another. Create a module named convert.py that has the following functions. Each function must return a float value, and take a single float parameter.

  • kilometers_to_miles
  • miles_to_kilometers
  • meters_per_second_to_miles_per_hour
  • miles_per_hour_to_meters_per_second

You'll need to figure out the arithmetic for each unit conversion. Note that there are 1.60934 kilometers per mile, 1000 meters per kilometer, and 3600 seconds per hour.

Half of the work for this exercise will be writing correct docstrings. Refer to the Docstring Requirements for Functions section as needed.

At the end of convert.py, add a "main block" for testing your functions:

if __name__ == "__main__":

    km = 4.9
    mi = kilometers_to_miles(km)
    print(f"{km:.1f} km = {mi:.1f} mi")

Your main block should call each function at least once and print the results using an f-string similar to the one shown above. For example, your main block might print:

4.9 km = 3.0 mi
4.9 mi = 7.9 km
4.9 mps = 11.0 mph
4.9 mph = 2.2 mps

Exercise 4.3 Date Analysis

Write a program named date_types.py that has one function date_analysis that returns three characteristics about the parameters:

  • The first parameter weekday will be the day of the week in numerical format (1–7) where 1 is Sunday, 2 is Monday, … 7 is Saturday
  • The second parameter month will be the month number (1–12) that represents the months January–December.
  • The third parameter mo_date will be the day in the month 1–31 that represents the day of the month.

Your function should return three values:

  • The first value will be the type of day ('weekday' or 'weekend', or return 'invalid' if outside the range of 1–7).
  • The second value will be the season (Fall [Sep–Nov], Winter [Dec–Feb], Spring [Mar–May], Summer [Jun–Aug], or 'Invalid' if outside that range).
  • The third value will be the portion of the month the date falls (0 for a number lower than one, 1 for 1st quarter, 2 for 2nd quarter, 3 for 3rd quarter, 4 for 4th quarter, or 5 for higher).

Notice that lowercase 'invalid' means the weekday was out of range, and uppercase 'Invalid' means the month was out of range.

You can test your code using a main block:

if __name__ == "__main__":
    print(date_analysis(6, 8, 18))
    print(date_analysis(0, 1, 26))

This output of this example is:

('weekday', 'Summer', 3)
('invalid', 'Winter', 4)

Exercise 4.4 Math Tricks

Write a program named math_tricks.py that has the following two functions:

  • sphere_volume(radius)

    Calculates the volume of a sphere with the provided radius. The function should return a float value. Here is the formula.

  • normal_pdf(mu, sigma, x)

    Evaluates the probability density function (at point x) for a normal distribution, given the mean (mu) and standard deviation (sigma). The function should return a float value.

The purpose of this exercise is to translate functions from mathematical notation (linked above) into Python code.

Exercise 4.5 Phone Number

Countries participating in the North American Numbering Plan use 10-digit phone numbers. To make phone numbers easier for humans to read, a dash is often displayed after the 3rd and 6th digits. Ex: The number 2024561414 is displayed as 202-456-1414.

Write a program named phone_number.py that includes the following two functions:

  • The format function formats the given integer as a phone number. Ex: Given the integer 1234567890, the function would return "123-456-7890" (exactly 12 characters, no extra spaces or newlines).

    def format(number):
        """Format a phone number for printing.
    
        Args:
            number (int): 10-digit phone number.
    
        Returns:
            str: Formatted as "123-456-7890".
        """
    
  • The checksum function returns the sum of the last four digits of a phone number. Ex: Given the integer 1234567890, the sum would be 7 + 8 + 9 + 0 = 24.

    def checksum(number):
        """Get the checksum of a phone number.
    
        Args:
            number (int): 10-digit phone number.
    
        Returns:
            int: Sum of the last four digits.
        """
    

Hint

The purpose of this exercise is to practice extracting digits from an integer using modulo and division. See the "getting digits" and "get prefix" examples in the textbook.

Warning

Your solution must not convert the number parameter to a string or list. Gradescope will reject submissions that use square brackets. Also, your solution must not use loops.

HW4 Reflection (required)

Submit the graded survey on Canvas after completing the assignment.