Functions are a wonderful tool to use while writing programs. In a nutshell, they just
allow you to write a piece of code ONE time and reuse it as much as you want within
As a matter of fact, you have already been using functions if you’ve followed this
tutorial: raw_input() and input(). These are built in functions, and there are many
more. Let’s try an easy example:
def new_function(): #defines our new function print "I'm in a function!" print "I'm out of function" new_function()
Now this is a very simple function. The first line simply defines the function. The
second line is a part of that function. Anything that is indented after the function is
considered part of it. When you name a function, it is common practice to add an
underscore in between words. This just makes it easier to recognize within the code.
Now you may be wondering what the paranthesis are for. We are able to put data into
the function in order to manipulate it. Like this:
def add_it(x, y): #define our function and have it call for two inputs print x + y #print the output x + y a = 50 #make two variables b = 100 add_it(a, b) #use our function to output our two variables added together
Notice that in this function we have x and y. These are considered variables only in
the function. If you try to call x or y outside of the function, it won’t work. So when
we call our function, we put in 2 variables, which effectively makes them x and y
within the function. This would also work with just plain numbers. Now its great to
manipulate the variables within the function, but lets say we want to keep that sum in
a global variable(variable that is seen by entire program).
def add_it(x, y): return x + y a = 50 b = 100 sum1 = add_it(a, b)
So in the previous code, we have added return. Your function will only return one
variable at a time (unless you use lists, covered later). So on the last line we just made
another variable that will be whatever value the function returns.
Another thing you can do with functions is specify a value when you are defining it. If
you don’t add that parameter in when you call the function, that value will be used.
def add_it(x, y, z = 13): return x + y + z add_it(1, 2) add_it(1, 2, 3)
I also give you an example of how you can just add numbers instead of first making
So as you can see functions are pretty simple. They are handy in making your code
neat, and definitely cut down on typing your program. Try the practice below!
Rewrite the menu program we have been working with to include functions for all the