Day 5: Pre-class Assignment: Thinking more about functions#

✅ Put your name here


Goals for Today’s Pre-Class Assignment#

By the end of this assignment, you should be able to:

  • More easily define and use functions in Python.

Assignment instructions#

Watch any videos below, read all included and linked to content, and complete any assigned programming problems. Please get started early, and come to office hours if you have any questions and make use of Slack!

This assignment is due by 7:59 p.m. the day before class, and should be uploaded into the “Pre-class assignments” submission folder for Day 5. Submission instructions can be found at the end of the notebook.

Part 1. Basic function structure#

The following short video serves as a reminder of the basic structure of a function and how you call functions that you write.

(If the YouTube video doesn’t work, you can access a back-up version on MediaSpace)

# Don't forget to watch the video in full-screen mode!
from IPython.display import YouTubeVideo  
YouTubeVideo("owglNL1KQf0",width=640,height=360)  # Writing functions

Part 2. Defining function input parameters#

Here’s another short video that reminds you how to define input parameters in Python. The video also points out how you can be specific about defining your input variable to be exactly what you want them to be, without worrying about the specific order of the variables.

(If the YouTube video doesn’t work, you can access a back-up version on MediaSpace)

# Don't forget to watch the video in full-screen mode!
from IPython.display import YouTubeVideo  
YouTubeVideo("CGRKqnoQGgM",width=640,height=360)  # Defining function inputs

Part 3. Setting default function values#

Now that we’re comfortable with writing functions and defining our input variables, this next video will show us how to define defaults for our input variables so that we don’t always have to define every single input value. This can be useful if we want a function to have a default mode of operation that works most of the time, but we still want to be able to change the values of some of the variables when necessary.

(If the YouTube video doesn’t work, you can access a back-up version on MediaSpace)

# Don't forget to watch the video in full-screen mode!
from IPython.display import YouTubeVideo  
YouTubeVideo("KeRxe9rll2Q",width=640,height=360)  # Default function parameters

Now let’s try to incorporate the things we learned in the last three videos into one small function.

✅  Question: Create a function that takes a person’s name as a string input and prints

Happy Birthday to < name >

where “< name >” is the person’s name that is given to the function. Set up the function so that if no name is given, it just says “Happy Birthday to you!”. You can give the function any name you want, but you should try to pick a function name that makes sense to someone else who might be using the function! Also, make sure to comment the function to explain what it does!

# Put your code here

Part 4. Writing functions that return values#

The previous three videos focused on defining the input variables for function, giving them defaults, and walking you through different ways to feed your input values into your functions, but they didn’t talk about returning variables from functions. In Python, we commonly want to write functions that not only take in a variety of input values, but we also want the function to return some new values when the function exits. For example, I might have a bit of code that looks like this:

def compute_average(v1, v2, v3):
    total = v1 + v2 + v3
    average = total/3
    return average

This function takes in three values, v1, v2, and v3, computes the average of those three values, and then returns that average. That means when I call the function, I can assign a new variable to be the value that is returned by the function. Specifically, I might do something that looks like this:

my_average = compute_average(4, -8, 12)

With that first line of code, I’ve create a new variable call my_average that stores the result of my compute_average function. It is important to note that if I don’t intentionally “catch” the returned value from my function, I won’t have access to that average value later on because the average variable in my function is local to the function. When we say that a variable is local to the function, it means that it can only be accessed in the place that it was created, inside the function. This means that if we simply do:

compute_average(4, -8, 12)

We aren’t actually storing the value we want. Python will print the value to the screen because we didn’t catch the value with a variable. Again, if I wanted to access that value later, I don’t have any way of doing that. The function computed the value, but we never stored the result anywhere, so calling the function was only useful if we wanted to see the number but didn’t care about using the number. Remembering to store the output from your functions is very important when writing code!

Important reminder: The moment a function comes across a return statement, it will exit the function and ignore any code that comes later in the function. This can actually be kind of useful if you want a function to return a value based on set of conditional statements. So I might write a function that looks like this:

def do_math(v1, v2, v3, calculation='sum'):
    if calculation == 'sum':
        total = v1 + v2 + v3
        return total
    elif calculation == 'average':
        total = v1 + v2 + v3
        average = total/3
        return average
        print("You didn't specificy a valid calculation option")

This function would allow me to run the following commands:

my_sum = do_math(4, -8, 12, calculation='sum')
my_average = do_math(4, -8, 12, calculation='average')
print("sum =", my_sum)
print("average =", my_average)

Question: What happens if I don’t use either ‘sum’ or ‘average’ for the calculation input in my function?

Put your answer here

5. Putting it all together#

Now, let’s try to put all of this into practice by revisiting a task from a previous pre-class assignment.

Do the following:

  1. Write function called x_squared.

  2. The function should take in a list of \(x\)-values of any length, but should have a default of [1,2,3].

  3. The function should return a new list of values that are \(x^2\) values of the original input values.

  4. Print the resulting new list.

Make sure your code works as intended!

# Put your code here

Assignment wrap-up#

For convenience, we’re going to include a couple of Python function references again so that you can check them out if you’re still looking for more information about functions:

Now, please fill out the form that appears when you run the code below or click this link to open the form in another tab (useful if you have issues with MSU login inside this window). You must completely fill this out in order to receive credit for the assignment!

from IPython.display import HTML

Congratulations, you’re done!#

Submit this assignment by uploading it to the course Desire2Learn web page. Go to the “Pre-class assignments” folder, find the appropriate dropbox link, and upload it there.

See you in class!