A Beginner's Python Tutorial/Functions

In our previous lesson, I said that we would delve into purposeful programming. That involves user input, and user input requires a thing called functions.

What are functions? Well, in effect, functions are little self-contained programs that perform a specific task, which you can incorporate into your own, larger programs. After you have created a function, you can use it at any time, in any place. This saves you the time and effort of having to retell the computer what to do every time it does a common task, for example getting the user to type something in.

Using a function
Python has lots of pre-made functions. You can use these pre-made functions right now, simply by 'calling' them. 'Calling' a function involves you giving a function input, and it will return a value (like a variable would) as output. Don't understand? Here is the general form that calling a function takes:


 * Code Example 1 - How to call a function

See? Easy.

function_name identifies which function it is you want to use (you'd figure...). For example, the function raw_input(this function has been renamed to input in Python 3), which will be the first function that we will use. Parameters are the values you pass to the function to tell it what it should do, and how to do it.. for example, if a function multiplies any given number by five, the stuff in parameters tells the function which number it should multiply by five. Put the number 70 into parameters, and the function will do 70×5.

Parameters and Returned Values - Communicating with Functions
Well, that's all well and good that the program can multiply a number by five, but what does it have to show for it? A warm fuzzy feeling? Your program needs to see the results of what happened, to see what 70 x 5 is, or to see if there is a problem somewhere (like you gave it a letter instead of a number). So how does a function show what it does?

Well, in effect, when a computer runs a function, it doesn't actually see the function name, but the result of what the function did. Variables do exactly the same thing - the computer doesn't see the variable name, it sees the value that the variable holds. Lets call this program that multiplies any number by five, multiply. You put the number you want multiplied in the brackets. So if you typed this:

The computer would actually see this:
 * Code Example 2 - Using a function

Note: don't bother typing in this code - multiply isn't a real function, unless you create it.
 * Code Example 3 - What the computer sees

The function ran itself, then returned a number to the main program, based on what parameters it was given.

Now let's try this with a real function, and see what it does. The function is called input, and asks the user to type in something. It then turns it into a string of text. Try the code below:

Say in the above program, you typed in 'hello' when it asked you to type something in. To the computer, this program would look like this:
 * Code Example 4 - Using input

Remember, a variable is just a stored value. To the computer, the variable 'a' doesn't look like 'a' - it looks like the value that is stored inside it. Functions are similar - to the main program (that is, the program that is running the function), they look like the value of what they give in return of running.
 * Code Example 5 - What the computer sees

A Calculator Program
Let's write another program, one that will act as a calculator. This time it will do something more adventurous than what we have done before. There will be a menu that will ask you whether you want to multiply two numbers together, add two numbers together, divide one number by another, or subtract one number from another. The only problem is that the raw_input function returns what you type in as a string, whereas we want the number 1, not the letter 1 (and yes, in Python, there is a difference).

Luckily, somebody wrote the function input (eval(input) in Python 3), which returns what you typed in to the main program - but crucially, as a number, not a letter. If you type an integer (a whole number), what comes out of input is an integer. And if you put that integer into a variable, the variable will be an integer-type variable, which means you can perform addition, subtraction and other mathematical operations on it.

Now, let's design this calculator properly. We want a menu that is returned to every time you finish adding, subtracting, etc. In other words, to loop (HINT!!!) while (BIG HINT!!!) you tell it the program should still run.

We want it to perform an option in the menu associated with the number you enter. That involves you typing in a number (a.k.a. input) and an if loop.

Let's write it out in understandable English first:

START PROGRAM print opening message
 * Code Example 6 - human-language example

while we let the program run, do this: #Print what options you have print Option 1 - add print Option 2 - subtract print Option 3 - multiply print Option 4 - divide print Option 5 - quit program ask the person what option they want and look for an integer if it is option 1: ask for first number ask for second number add them together display the result on screen if it is option 2: ask for first number ask for second number subtract one from the other display the result on screen if it is option 3: ask for first number ask for second number multiply them display the result on screen if it is option 4: ask for first number ask for second number divide the first by the second display the result on screen if it is option 5: tell the loop to stop Display a goodbye message on screen END PROGRAM Let's put this in something that Python can understand:

Wow! That is an impressive program! Paste it into Python IDLE, save it as 'calculator.py' and run it. Play around with it - try all options, entering in integers (numbers without decimal points), and numbers with stuff after the decimal point (known in programming as a floating point). Try typing in text, and see how the program chucks a minor fit, and stops running (That can be dealt with, using error handling, which we can address later.)
 * Code Example 7 - Python version of menu

Define Your Own Functions
Well, it is all well and good that you can use other people's functions, but what if you want to write your own functions, to save time, and maybe use them in other programs? This is where the 'def' operator comes in. (An operator is just something that tells python what to do, e.g. the '+' operator tells python to add things, the 'if' operator tells python to do something if conditions are met.)

This is how the 'def' operator works:

def function_name(parameter_1, parameter_2): {this is the code in the function} {more code} {more code} return {value to return to the main program} {this code isn't in the function} {because it isn't indented} function_name is the name of the function. You write the code that is in the function below that line, and have it indented. (We will worry about parameter_1 and parameter_2 later, for now imagine there is nothing between the parentheses.
 * Code Example 8 - The def operator
 * 1) remember to put a colon ":" at the end
 * 2) of the line that starts with 'def'

Functions run completely independent of the main program. Remember when I said that when the computer comes to a function, it doesn't see the function, but a value, that the function returns? Here's the quote:

"To the computer, the variable 'a' doesn't look like 'a' - it looks like the value that is stored inside it. Functions are similar - to the main program (that is, the program that is running the function), they look like the value of what they give in return of running."

A function is like a miniature program that some parameters are given to - it then runs itself, and then returns a value. Your main program sees only the returned value. If that function flew to the moon and back, and then at the end had:

then all your program would see is the string "hello", where the name of the function was. It would have no idea what else the program did.
 * Code Example 9 - return

Because it is a separate program, a function doesn't see any of the variables that are in your main program, and your main program doesn't see any of the variables that are in a function. For example, here is a function that prints the words "hello" onscreen, and then returns the number '1234' to the main program:

Think about the last line of code above. What did it do? Type in the program (you can skip the comments), and see what it does. The output looks like this:
 * Code Example 10 - using return

hello 1234 So what happened?
 * Code Example 11 - the output

when 'def hello' was run, a function called 'hello' was created When the line 'hello' was run, the function 'hello' was executed (The code inside it was run) The function 'hello' printed "hello" onscreen, then returned the number '1234' back to the main program The main program now sees the line as 'print 1234' and as a result, printed '1234' That accounts for everything that happened. remember, that the main program had NO IDEA that the words "hello" were printed onscreen. All it saw was '1234', and printed that onscreen.

Passing Parameters to Functions
There is one more thing we will cover in this (monstrously huge) lesson - passing parameters to a function. Think back to how we defined functions:

def function_name(parameter_1,parameter_2): {this is the code in the function} {more code} {more code} return {value (e.g. text or number) to return to the main program} Where parameter_1 and parameter_2 are (between the parentheses), you put the names of variables that you want to put the parameters into. Put as many as you need, just have them separated by commas. When you run a function, the first value you put inside the parentheses would go into the variable where parameter_1 is. The second one (after the first comma) would go to the variable where parameter_2 is. This goes on for however many parameters there are in the function (from zero, to the sky) For example:
 * Code Example 12 - Defining functions with parameters

When you run the function above, you would type in something like this:. The first value (that is, "meat") would be put into the variable called first_word. The second value inside the brackets (that is, "eater") would be put into the variable called second_word, and so on. This is how values are passed from the main program to functions - inside the parentheses, after the function name.
 * Code Example 13 - how parameters work

A Final Program
Think back to that calculator program. Did it look a bit messy to you? I think it did, so lets re-write it, with functions.

To design - First we will define all the functions we are going to use with the 'def' operator (still remember what an operator is ;) ). Then we will have the main program, with all that messy code replaced with nice, neat functions. This will make it so much easier to look at again in the future.

The initial program had 34 lines of code. The new one actually had 35 lines of code! It is a little longer, but if you look at it the right way, it is actually simpler.
 * Code Example 14 - Calculator program

You defined all your functions at the top. This really isn't part of your main program - they are just lots of little programs, that you will call upon later. You could even re-use these in another program if you needed them, and didn't want to tell the computer how to add and subtract again.

If you look at the main part of the program (between the line 'loop = 1' and 'print "Thank you for..."'), it is only 15 lines of code. That means that if you wanted to write this program differently, you would only have to write 15 or so lines, as opposed to the 34 lines you would normally have to without functions.

Tricky Ways You Can Pass Parameters
Finally, as a bit of an interlude, I will explain what the line  means.

I wanted to fit everything onto one line, with as few variables as possible. Remember what functions look like to the main program? Whatever value they return. If the numbers you passed to the add function were 2 and 30, the main program would see this:

The add program would then run, adding 2 and 30, then printing the result. The add program has no 'return' operator - it doesn't return anything to the main program. It simply adds two numbers and prints them onscreen, and the main program doesn't see anything of it.
 * Code Example 15 - The results of fancy parameter work

Instead of  as the parameters for the add program, you could have variables. For example,

For the above, remember that the function you are passing the variables to cannot change the variables themselves - they are simply used as values. You could even put the values straight into the function:
 * Code Example 16 - variables as parameters

This is because the only thing the function sees are the values that are passed on as parameters. Those values are put into the variables that are mentioned when 'add' is defined (the line 'def add(a,b)' ). The function then uses those parameters to do its job.
 * Code Example 17 - the end result

In short:


 * the only thing functions see of the main program is the parameters that are passed to it
 * the only thing the main program sees of functions is the returned value that it passes back