Python Tutorial-Functions

Functions are useful bits of code that help streamline your overall program. Functions are also used for code that you think will be used elsewhere in your program. Arguments can be added to your function to make it even more useful and flexible as you will see in a few moments.

Functions are defined by using def. That’s simple enough, right? Let’s take a look..

Now at this point in our tutorials I am not going to tell you when to use IDLE and when to open a new file to create the program. I am hoping by now it has sunk in.

OK, this is a rather simple function (and a long approach just to print something out) but I am just showing you how a function is created and works. If you entered the above and ran it then the result would be This is my function.

Let’s dissect the code above. In the first line we defined a function. The second line is the actual function (what we want Python to do). The third line calls the function. Probably the most important thing to note is the the function has to be defined before it is called. Which if you think about it makes sense. Pay special attention to the syntax!

Here’s one with an argument.

What did you get when you used this code? Don’t do like I did and spell myArgument incorrectly. This time in line one we defined a function called myArgument and added arguments to it (num1 and num2). In the second line we told Python what we want to do with the function and in the third line we called the function and supplied the values for the arguments. Are you starting to see the usefulness of this? You should have gotten an output of 300.

Global Variables & Local Variables

Show and tell time!

This will create an error because we are attempting to print variable (a) outside of the function, but variable (a) was declared inside the function. As a result you get this error:

Traceback (most recent call last):
File “C:/Python33/function.py”, line 4, in
print(a)
NameError: name ‘a’ is not defined

However; Python let’s you declare a variable globally which will then allow you to use the variable within the function. This is how it should look:

Because we declared our variable (a) outside of the function it can be used anywhere in the program. It’s globally accessible anywhere in your program now, even inside the function. If we try to declare the variable inside the function as we did in the previous example (a) is only available locally to that function. When we try to use it outside of the function Python does not know what it is.

Alright, that’s it for now..go play with a Python…just not a 30 foot one that eats alligators whole.