Functions

All new tutorial are submitted here.
They will be moved to the main Tutorials section once they have been approved by mods and admins.

Functions

Postby alext6453 » Wed Feb 20, 2013 11:26 am

Why Use Functions?

The first thing that one must know with functions is that they are not essential. One can still write their
program without any functions, however when debugging all that unsorted code can be very confusing, especially
for beginners.

One should use functions in their programs because they allow one to break each part of one's program into
managable chunks.


The syntax for a function is as follows:

Code: Select all
def NAME(PARAMETERS): # Don't forget that colon, alot of people do. :)
    """Purpose of Function""" # Indent 4 spaces like everything else.
    STATEMENTS


The first thing that we can see is the 'def'. This tells python that this is a function, and will skip over it
untill it is called.

The next thing here is the name of the function. This should be clear, and memorable. I highly recommend that
one never has a function name that is the same as the name of a global variable. One can, but it is considered
to be bad form, and is very confusing for one as the programmer.

Next we have the parameters of the function. It is customary for parameters to be single letters that
represent what needs to go into your function. The values of these parameters are specified when the function
is called

This is optional, but it is a very good idea to state the purpose of one's function in triple quotation marks,
as when programming you can see what the function is supposed to do. You may be wondering why we did not simply
leave a comment with '#'. We use the quotes because the purpose of the function can be summoned, whereas a
standard comment has no effect at all.

Next we have the statements. These will manipulate the values and change them. You know, just print commands
and stuff.

Lets move on to some examples, and some common mistakes.

Code: Select all
def squarenum(n):
    """Return the square of any number"""
    return n ** 2

print(squarenum(5))


This type of function is called a fruitful function, because the function returns a value. Now alot of people
make this mistake in functions like these, so read carefully.


Alot of novices will do this:

Code: Select all
def squarenum(n):
    """Return the square of any number"""
    result = n ** 2

print(result)


This will return an error. Why? Because the 'result' is what is called a local variable. It is removed when the
function ends, so when this person tries to print 'result' they get an error saying it was not defined. The way
that will work is shown first, where I print the function where I used the return command.

Another common error is when people do not use the names of parameters in the body of their functions, but use
the names of a global input variable, which was earlier defined as a parameter.

Here is an example:

Code: Select all
def squarenum(n):
    """Return the square of any number"""
    return number ** 2 # Another dumb mistake. :P

number = int(input("Please put a number"))
print(squarenum(5))


So that was my tutorial on functions. I hope this will help you make and improve your own programs!
Occupation GCSE Computing Student.
Languages Python 3, JavaScript, HTML, Batch.
python-forum.org is epic!
User avatar
alext6453
 
Posts: 4
Joined: Tue Feb 19, 2013 12:57 pm
Location: Hertfordshire, England.

Re: Functions

Postby micseydel » Wed Feb 20, 2013 6:48 pm

alext6453 wrote:
Code: Select all
def NAME(PARAMETERS): # Don't forget that colon, alot of people do. :)
    """Purpose of Function""" # Indent 4 spaces like everything else.
    STATEMENTS

Note that ALL CAPS variable names are not considered appropriate for the name or parameters of a function.

The first thing that we can see is the 'def'. This tells python that this is a function, and will skip over it
untill it is called.

Strictly speaking, it does not "skip over it". It evaluates it, and stores it, and it simply isn't used until it is called.

The next thing here is the name of the function. This should be clear, and memorable. I highly recommend that
one never has a function name that is the same as the name of a global variable. One can, but it is considered
to be bad form, and is very confusing for one as the programmer.

I'm not sure what you mean by this. Functions are typically global, so if you have a variable with the same name as a function, then one or the other will not be available (whichever was defined most recently is actually available).

Next we have the parameters of the function. It is customary for parameters to be single letters that
represent what needs to go into your function.

This is an over generalization. Single-letter variable names should be used sparingly. Although they are generally considered fine for numbers in simple mathematical functions, meaningful variable names are vital, especially when there are multiple parameters to the function. For example, I was recently making a Contact class and passed in parameters "name" and "number" for it, and clearly those are better names than any single-letter names.

it is a very good idea to state the purpose of one's function in triple quotation marks,

Any form of quotes will work. I believe PEP 8 specifies triple double-quotes, but this is something from PEP 8 I tend to not take as seriously, because I feel like it makes my code noisy and verbose. I'm curious what the rest of the community thinks about the convention.

I also feel like the usefulness of the doc string is understated. A good IDE will notice the doc string and can provide a popup with the doc string for the function while you're typing it. Many people dislike IDLE, but IDLE has this feature for interactive sessions, and I love it (try it yourself: define a function with a doc string, and then when you go to call the function, as soon as you type the open paren, a little popup will appear).

Code: Select all
def squarenum(n):
    """Return the square of any number"""
    return number ** 2 # Another dumb mistake. :P

number = int(input("Please put a number"))
print(squarenum(5))

Just to be explicit, the undesired result of this isn't that it results in an error (which would be nice in this case) but rather that the function uses the global variable number. A way to avoid this kind of mistake is to wrap the "main" code in a main() function, and put this at the end of your code
Code: Select all
if __name__ == '__main__':
    main()

Also worth noting here is that most people will be using Python 2, but this code is Python 3.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1223
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA


Return to Tutorial Submissions

Who is online

Users browsing this forum: No registered users and 1 guest