In this part of the series we are going to be exploring functions, including how to define them, using parameters, and retuning values. Functions are one of the most used features in programming.
A function is a reusable block of statements which can be used from multiple places and multiple times. Functions usually have a name, which is used to identify it when you want to use it. Running a function is typically known as "calling" it.
Defining a Function
To write a function you use the "def" keyword, which is short for "define." The name of the function comes after the "def," then a pair of brackets which can optionally contain parameters, and then a colon. The block of statements which make up the body of the function follows from the next line, indented as mentioned in a previous part of the series.
This may sound quite complex, but in reality it is actually pretty simple.
For example, here's a simple program with a function:
def say_hello(): print 'Hello world!' # Call the function say_hello()
If you run that program now, it should print out, "Hello world!"
Most of the time you use functions, you will want to perform some actions on some data. Using parameters, you can pass this information into the function. To define a parameter, simply insert a name of the parameter between the brackets. For example:
def say_hello(name): print 'Hello', name # Call the function with a parameter say_hello('Peter')
If you run this program, it should print out, "Hello Peter". You don't only need to pass literal values to the function, you can also pass variables. For example:
my_name = 'Peter' say_hello(my_name)
You can declare variables inside functions, just like you can do it anywhere else. Local variables, however, are only available inside the function, and only for the duration of the function call.
Local variables can have the same names as variables outside of the function because they only work in the context of the function they are declared in. This is known as /scope/.
Let's look at an example:
def say_hello(name): print 'Hello', name name = 'world' print 'Hello', name name = 'Peter' say_hello(name) print name
If you run this program your output should look like this:
Hello Peter Hello world Peter
Here you can see that while we changed the "name" variable in the function, but the "name" variable outside the function never changed.
We've seen that variables used inside a function are called local variables, but you're probably wondering what those "outside" variables are called. Variables which exist outside of functions and are available inside functions are called global variables.
Here's a simple example of how a global variable works:
name = 'Peter' def say_hello(): print 'Hello', name say_hello()
The output is exactly as we expect:
As we discussed earlier, if you try to modify that global variable inside the function, it becomes a local variable. What happens if we want to change that global variable? Just changing it obviously isn't going to work, but fortunately Python has the "global" keyword which specifies that a variable within a function is global and not local. With this keyword we can modify a global variable within a function.
Let's look at an example:
name = 'Peter' def say_hello(): global name print 'Hello', name name = 'James' say_hello() print name
If you run this program, your output looks like this:
Hello Peter James
As you can see, this time the outside variable was changed.
Sometimes while developing you don't want to have to supply a value for every parameter in a function call, but you want to be able to use those extra parameters in other situations. In Python you can specify that a parameter has a "default" value, a value that is set when you don't supply that parameter.
Here's an example:
def say_hello(name='World'): print 'Hello', name say_hello('Peter') say_hello()
If you run this program, then you should see the following:
Hello Peter Hello World
As you can see in the above example, when we didn't supply the parameter, it passed the value we specified in the declaration of the function.
Returning A Value
Up until now we have simply executed a function and let the function take over. In most cases when programming, you're not going to execute functions like that, you'll want to run the function and then be able to examine its output for further processing. In Python you can pass the output of a function back by using the "return" keyword:
def say_hello(name): return 'Hello ' + name greeting = say_hello('Peter') print greeting
Now, when we run this program, we see the following:
In addition to returning a value, the return value stops the execution of the function and exits immediately. You can use this to break out of a function without having to execute the entire function.
def say_hello(name): if name == 'Peter': return 'Welcome back, Peter!' greeting = 'Hello ' + name return greeting hello = say_hello('Peter') print hello hello2 = say_hello('James') print hello2
If you run this program, you'll see that the output looks something like this:
Welcome back, Peter! Hello James
As you can see, as soon as 'Peter' was passed in to the function, the if statement ran, and then the return keyword caused the text, 'Welcome back, Peter' to be returned. When another name was passed in, the function skipped the if statement and the standard greeting was returned.
Supplying a value to the return statement is optional. If you don't supply a value, the return statement returns None. A function without a return statement also returns None. Note that as shown in some of the previous examples, the return value of a function can be ignored by simply not capturing the value.
On the other hand, if you want to create a placeholder for a function without writing any code, simply set the body of the function to the "pass" keyword. This keyword tells Python that the function does not contain any code and causes it to return None.
def say_goodbye(): pass print say_goodbye()
If you run this program, the output will look like this:
With this you can set up different parts of a program without having to actually write the functions until you need to.
That's all for this tutorial, at this point you should be able to write a few basic programs. Try writing a program that calculates the product of two numbers by multiplying them with each other in a function and returning the result.
Update: Part 6