Functions are Powerful

Functions are an important part of programming. Functions do two things for us.

When we write a function we must do two things. We must define the function. That part starts with the keyword def.

Once we have defined a function we can use it in our program. Using a function means we write the name, followed by a left paren, the values we want to pass to the function, and then finally a right paren.

When we are defining a function we must answer three questions.

  1. What should we name the function. Generally you should pick a name that makes sense for what you are doing?
  2. What values need to be given to the function so it can do its job?
  3. What type of value should be returned from the function?

Answering these questions will help you in understanding what your function needs to do and hopefully how it should be written.

Defining and Using Functions

In the last lesson we learned how to draw a polygon with an arbitrary number of sides. In this lesson we'll learn how to make the code in that program more useful. Defining and using functions in Python helps us reuse the code we write and also helps to break up our programs into manageable pieces. Let's start with an example from Mathematics. In math, we can define a function

f(x) = 2*sin(x)

This is a function called f that can be called to find the value of 2 * sin(x) for some x. We say that x is given to the function and it returns 2 * sin(x). When working with functions it is important to identify what the function is given and what it returns.

To write this in Python we can write a program like the one below. This program defines the function f and then uses it to plot the function between -10 and 10 on the x axis.

In the program above there are two functions defined. The first function is f, the one you saw above. The other function is named main. The function f is given a real number and returns 2 times the sin of that real number. The main function isn't given anything. That's the reason for the () in the

def main():

The main function also does not return anything. When this program is run the def f and def main lines, along with all the code that is inside of each of them, do not do anything until the last line of the program above when main() is called. The program begins execution by calling main() on the last line of the file.

Now You Try It

Now it's your turn. Try writing a program that plots

g(x) = x**4/4.0 - x**3/3.0 - 3 * x**2

In Python the exponent operator is ** so x**2 is x squared. Make sure that the graph of the function does not go off the bottom of the screen when your run it. What do you have to change to make that happen?

>> Next Lesson