Topic - Creating your own Functions


Topics:

Materials:


Motivating Functions

The topic for this week involves creating your own functions.  Recall the the definition of a function is:

A named segment of code that you can call over and over again.  Often includes parameters to change how the function performs or what it produces.

In this brief video we review functions from Scratch and mathematics and motivate why we want them in a programming language like Python.

VIDEO : Motivating Functions (7 minutes)

 


A Function for Windchill

We are getting close to that time of year where the weather forecasters will start talking about the windchill.  Where does that number come from?  It turns out that this is a fairly standardized formula.  The following was takeng from the wikipedia page about windchill.

empty

Let's look at how we can create a function in Python that calculates the windchill.

VIDEO - Windchill Function, part 1 (18 minutes)

VIDEO - Windchill Function, part 2 (6 minutes)

 


Collatz Conjecture

This example relates to a famous conjecture in mathematics that deals with a sequence of numbers.  The sequence begins with any positive integer n.  Each following term in the sequence is calculated using the following:

In other words, if a term is even, the following term is half of n.  If a term is odd, the following term is 3n+1.

The Collatz Conjecture states that for all positive integers N this sequence will eventually reach the value 1 after which it repeats 1, 4, 2, forever.   (The wikipedia page for the Collatz Conjecture)

VIDEO - Making a function for the Collatz Conjecture (20 minutes)

 

 


Boolean Functions - Is a String an Integer

In an earlier program you were faced with the problem that you wanted to read in some input from the user that sometimes was a word ("quit") and sometimes was an integer. Many of you hit a snag that you tried to do

int(userInput)

and then discovered that if the userInput was the word "quit" that it crashed the program.  In this activity we write a helper function that we can use first that will tell us if the function is a valid integer or not.

VIDEO - Making a Boolean Function  (22 minutes)

 


Functions with Lists

At the end of unit 2 you started looking at the idea of Lists of data. While we showed you some examples in the lecture/prep materials we didn't have you program any code yourself that used a list.  This was, in part, because it's annoying to provide lists to the program via command line/user input.  But now that we have functions we will use lists a LOT more because it is much easier to create or work with lists.

In this activity we will work with functions that use lists as parameters and, in one case, return lists as a result.

VIDEO - Functions that use lists (15 minutes)