Session 17

An Introduction to Functions


CS 1510
Introduction to Computing


Quick Exercise

Here's a quickie. And it doesn't require code!

Write down the names of all the Python functions that we have used this semester.

Here is my list. Am I missing any?

Now:

Group the functions according to their purpose.

... I see three basic types of function there: I/O, converting between types, and calculation. ... two types of conversion, too.

What about + and *? What about str.strip() and str.find()? The former are operators. They work like functions, but with a very different syntax. The latter are string methods. They work like functions, with a slightly different syntax.



A Look at Functions

What is a function?

a relationship between values

... conceptually, a single operation, even if takes several Python statements to perform. We give it a name.

... takes zero or more arguments. The function performs its operation with these values.

... produces a single value.     (digression)

Example: len().

len() computes the length of a string, that is, the number of characters in the string. It expects on argument, a string, and returns an integer as its value.

... what happens when we call the function, say:

    my_str = input('Enter a string: ')

    # What happens here?
    length = len(my_str)

    print(length)

Example: len().

Trace the example in detail...

Notice: The len() function doesn't know anything about our code, including the names of our variables. It doesn't even know if we are passing it a variable:

    >>> len('foobar')
    6

... or if we are storing its return value in a variable:

    >>> print( len('foobar') )
    6

When we use a function, we can't assume that it will know the context in which it is being used. We can talk to it only by passing arguments and using the return value.



Defining a Function

Python gives us many pre-defined functions, which are sometimes called primitive functions. We can also write our own.

Suppose that we need to find out which of two strings, old_name and new_name, is longer. Unfortunately, we have forgotten about the primitive function, len(), and we do not have access to the great God, Google. What are we to do?

We know how to write a loop to count the characters in a string:

    count_old = 0
    for ch in old_name:
        count_old += 1

We could repeat this code for the second string:

    count_old = 0
    for ch in old_name:
        count_old += 1

    count_new = 0
    for ch in new_name:
        count_new += 1

and then compare them:

    ... count_old < count_new ...

This program works fine, but... The two loops were identical. They implement a single operation: count the number of characters in a string. We can define this operation as a Python function:

    def length(str):
        count = 0
        for ch in str:
            count += 1
        return count

... the anatomy of a function definition (Page 261 in your text):

... parameter versus argument. ... a subtle distinction. Many people consider them to be interchangeable, at least when speaking informally.

... names of parameters and local variables. ... more general. ... work for any string. ... not connected to the caller in any way but the values of the arguments and the return value.

This allows us to write a new version of of our program, with the two loops replaced by two function calls:

    count_old = length(old_name)
    count_new = length(new_name)

The adventure is just beginning.



Quick List of Primitive Python Functions We Have Used

This is the list I came up with in thirty seconds or so:

    int()
    float()
    str()
    input()
    print()
    ord()
    chr()
    math.sqrt()
    len()

To be honest, I forgot about len() and added it a few minutes later. Am I missing any others? Ah... range() -- good job!     (return to session)



Digression on Return Values

Even print() return a value:

    >>> value = print('foo')
    foo
    >>> value
    >>> 

That's unusual, though. Whatever IDLE prints as the value returned by the fuinction, we cannot see it.

Don't worry about print()'s return value. It is an exception, and we don't use it.     (return to session)



Wrap Up



Eugene Wallingford ..... wallingf@cs.uni.edu ..... October 21, 2014