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?