Lab: First Function

Got to start somewhere

In this lab, we're going to write a simple interactive program and then re-write it using functions to organize our code.

Part I: Convert Me

Write a simple Python program to convert temperature from Fahrenheit to Celcius. Ask the user for a temperature in Fahrenheit, then print out the result in Celcius, like "32 degees Fahrenheit is 0 degrees Celcius".

Part II: Clean up Your Mess

The little program you just wrote combines several steps that we would like to break up:

  • Ask the user for a temperature
  • Convert it
  • Display the answer

Functions allow us to organize code into simple, re-usable, testable blocks. The conversion from Fahrenheit to Celcius is a good example of a straightforward function, much like square root, cosine and others we've looked at.

Here is an example of a silly function that adds two numbers together, for your reference:

def silly_adder(x, y):
  """This function returns the sum of x and y"""
  return x + y

Notice the descriptive string on the second line in triple-quotes (triple-quotes allow for multi-line strings). This is called a docstring, and it is the standard practice in Python to document what a function does. In particular, most functions document how the input parameters are used to generate the return value.

So far in this class, we've been just putting code into a Python file with no functions. This is fine for testing and small scripts, but not a good general practice. Instead, most programs define a main function that holds the main program code, and then call that to kick it off. In other words, the program does not start and the top of the file and go through to the bottom, it starts with the main function and goes through whatever other functions are called from main.

In a new file, using the template below, re-write your converter program using functions!

# define your conversion function here. it should:
# - take in one parameter, a temperature in Fahrenheit
# - return the corresponding temperature in Celcius
# - don't forget a docstring!


# here is the main function definition which contains the highest-level
#  steps that make up the program
def main():
    """
    This interactive console program gets a temperature in Fahrenheit
    from the user, and displays the conversion to Celcius.
    """

    # as the user for a temperature in Fahrenheit


    # use your function above to convert it to Celcius


    # display the converted temperature


# so far you've just defined functions, this line is what calls main to
#  start off the program
main()