Python Functions

What are functions?

A block of code, usually designed to perform a specific job

Functions can return values that can be evaluated in various ways

They can be assigned to variables, evaluated in control statements, etc.

We have already used functions:

>>> length = len('fred')

>>> print length

4

len() is a function that returns the number of characters in the string given as an argument

An argument is a piece of data passed to a function through a parameter (the variable transferring the from the caller to the function)

In this example, len() takes the argument 'fred�and returns the value 4

We will learn how to write functions that accept arguments as parameters

Functions don�t have to return values, however

They sometimes act as a convenient way to organize a bunch of related code to do some task

No one is forcing you to write function definitions, but�

If you are repeatedly performing a relatively complicated task, writing a working function once and calling it many times reduces chances of making mistakes

Calling a function means to use it in an expression

In this expression:

>>> length = len('fred')

We are calling (or using) len() to find out how many characters are in 'fred'

It also makes your programs much more readable

We will now find out how to write our own function definitions

Writing function definitions

We�ll write a function definition for capitalize() that will make the first letter of its argument upper case

Note: for simplicity, we will not do error checking here�see below for safer version

Our function will take an argument that it assumes will be a string

It will convert the first character to upper case and paste it onto the front of the remainder of the word

It then returns the modified word

If you want to create a function definition in with the Python console,

Use spaces for indents

Keep the number of spaces you use for a given indent level constant

To end the function definition, hit Enter on an empty line

This will get you back to the >>> prompt

>>> # The definition of capitalize()

>>> # The keyword def introduces a function definition, followed by the

>>> # function name, 0 or more parameters, and a : character.

>>> # Our function has 1 parameter. The first line is unindented

>>> # The function block must be indented some number of spaces

>>> def capitalize(word):

...���� # Get the first character of the argument����

...���� first_char = word[0]

...���� # Save the converted upper case first character���

...���� uc_first_char = first_char.upper()

...���� # Add the upper case first character to the rest of word

...���� # and return the combined string

...���� return uc_first_char + word[1:]

...

>>> capitalize('fred')

'Fred'

We are not going to bother writing function definitions on the Python command line because it�s too painful

Open up Sublime Text and do it there

Here is a script that exercises functions