Last updated: Monday 1st March 2021, 11:38 PT, AD

 

PLEASE REFRESH THIS PAGE TO GET THE LATEST VERSION







And now for something
completely different . . .

Part 5

 

Python 3 Functions

 

6.1 Introduction to Functions

6.2 Python's Built-in Functions

6.3 Programmer-defined Functions

 

 

 

 

Introduction to Functions

 

Most real-world computer programs are very large programs.

 

The best way to manage the development of large programs

is to construct them from smaller parts. This technique is called

divide and conquer.

 

 

 

 

Programs are normally made up of subparts...

 

There may be a subpart to handle data input,

another subpart to handle the processing of the data,

and another subpart to handle data output.

 

These subparts or subprograms are given a name and are considered

as a separate entity. They are known as functions.

 

 

 

 

Functions are executed simply by calling their name.

 

You write a function once, and you may call it (make it execute - i.e. run)

as many times as you wish in the same program.

 

You may use the same function in different programs.

 

You may package similar functions into a single module for ease of use.

 

 

 

Functions can receive data to be processed within the function, and . . .

. . . functions can return data to the part of the program that called the function.

 

 

 

 

Top-Down Design

 

Top-down design is breaking down a problem into

smaller and smaller problems,

until the smallest problem can be implemented in a function

which fits onto a single screen of the code editor...

 

 

Program design known as structured program design or top-down program design

requires that programming problems are broken down

into small problems which are executed one at a time. . .

 

 

The goal of top-down design is

to break a problem into individual tasks, or modules,

that can easily be transcribed into pseudocode

and then coded as a function.

 

 

Modules continue to be broken down into further modules,

until at the lowest level,

the modules are small enough

to be coded into a single function which performs a single task.

 

 

 

 

 

Advantages of Functions

 

*      allows programs to be written by teams

*      manageable program development

*      software reusability

*      avoidance of code repetition

*      makes programs more understandable

*      makes programs easier to debug

 

 

 

 

 

 

Structured Programming

 

A structured program

is one which is based on a modular design

and uses only the three types of control structures:

sequences, decisions and loops.

 

 

 

Structured Programs

 

*      use functions

*      have sequential structure (statements in sequence)

*      use the decision structure (if statement)

*      use the loop structure (while statement)

 

 

 

Advantages of Structured Programs

 

*      Easy to write

*      Easy to debug

*      Easy to understand

*      Easy to change

 

 

 

 

 

6.2 Python's Built-in Functions

 

Python has a huge selection

of built-in functions ready for immediate use.

These are packaged into modules according to their purpose.

 

 

 

The math module is part of Python's standard library.

Python's standard library is a collection of modules

providing functions such as

math calculations,

string (text) manipulations,

web programming,

graphics programming,

as well as many other operations.

 

 

 

 

Python's Standard Library

 

Python's standard library is provided

as part of the core Python language

and is located in the library folder (\lib)

of the Python installation.

 

 

 

 

Python's math Module

 

The math module contains functions

that allow programmers to perform

certain mathematical calculations,

for example,

to find the square root of a number.

 

 

 

 

Using Python's math Functions

 

To use a built-in function

that is defined in a module,

a program must first import the module,

using the keyword import, e.g.

 

import math

 

 

See:

http://docs.python.org/3.0/library/math.html

 

 

 

Calling a built-in function

 

After the module has been imported,

the program can invoke (call) functions in that module

by using the module's name, followed by a dot (.)

and the function's name followed by parentheses...

 

modulename.functionname()

 

import math

print (math.sqrt(16))

print (math.sqrt(16.5))

 

 

# see program 06-01.py

# of www.annedawson.net/python3programs.html

 

http://www.annedawson.net/python3programs.html

 

 

Objects sent to a function

 

Any object or objects sent to a function

are known as the argument(s) of the function,

and are placed between the brackets after the function's name.

 

print (math.sqrt(16))

 

In the example above, 16 is the argument.

 

 

Depending on how it is defined,

a function may have zero, one or many arguments.

 

 

 

 

To print a list of the functions in the math module

 

import math

print (math)

print (dir(math))

 

# see program 06-02.py

# of www.annedawson.net/python3programs.html

 

http://www.annedawson.net/python3programs.html

 

 

 

Python's Always-Available Built-in Functions

 

See:

http://docs.python.org/3.0/library/functions.html

 

 

 

The link above lists all the

always-available Python functions in alphabetical order.

Note: you do not need to use an import statement to use these functions.

 

 

 

 

 

 

Some Always-Available Functions

 

This is a list of always-available functions

that we've used in this course so far:

 

 

print (value)

 

float (x)

 

id (object)

 

int (x)

 

range ([start,] stop[, step])

 

input ([prompt])

 

str (object)

 

type (object)

 

 

 

 



6.3 Programmer-defined Functions

 

Python's standard library modules

simplify the job of the programmer,

because programmers only have to write new functions

if a built-in function isn't sufficient for the job in hand.

 

 

 

 

Creating and Using a Programmer-Defined Function

 

The Function Definition

 

 

The syntax of a function definition is:

 

def function-name( parameter-list ):

    statements

 

 

Note that the statements must be indented.

 

def is one of Python 3's thirty three (33) keywords.

 

Run the following program to see the list of Python's keywords:

 

import keyword

print (keyword.kwlist)

 

 

The function definition does not execute the function body.

The function body (block of statements) is executed only when the function is called.

 

 

An Example Program containing a Programmer-Defined Function

 

 

 

def cube( y ):

    return y * y * y

 

# prints the cube of numbers 1 to 5

for x in range(1,6):

    print (cube(x))

 

print ("last value of x is:",x)

 

# see program 06-03.py

# of www.annedawson.net/python3programs.html

 

http://www.annedawson.net/python3programs.html

 

Note that the value of x is not changed by the function.

 

 

 

 

 

Placement of Function Definitions

 

 

A Python program may have one or more function definitions,

but the definitions must be placed at a position in the code

before the corresponding function call statement.

We usually place function definitions at the top of the code,

after the heading comments.

 

 

 

An Example Program containing

Two Programmer-Defined Functions

 

def cube( y ):

    return y * y * y

 

def doubleIt ( z ):

    return 2 * z

 

print ("1 to 5 cubed")

for x in range(1,6):

    print (cube(x))

print()

print()

 

print ("1 to 5 doubled")

for x in range(1,6):

    print (doubleIt(x))

 

# see program 06-04.py

# of www.annedawson.net/python3programs.html

 

http://www.annedawson.net/python3programs.html

 

 

 

 

 

Saving Programmer-Defined Functions in a Separate File (Module)

 

 

def cube( y ):

    return y * y * y

 

def doubleIt ( z ):

    return 2 * z

 

# see program myFunctions.py

# of www.annedawson.net/python3programs.html

 

http://www.annedawson.net/python3programs.html

 

 

Functions saved in a separate file (module)

can be called from another program

 

 

import myFunctions

 

print ("1 to 5 cubed")

for x in range(1,6):

    print (myFunctions.cube(x))

print()

print()

 

print ("1 to 5 doubled" )

for x in range(1,6):

    print (myFunctions.doubleIt(x))

 

 

# see program 06-05.py

# of www.annedawson.net/python3programs.html

 

http://www.annedawson.net/python3programs.html

 

 

 

Python automatically creates

a compiled version of function files

 

This means that they don't need to be recompiled into byte code

every time they're used, only when they're changed.

 

This significantly speeds up execution time of programs which use functions.

 

Note the compiled version of the myFunctions.py file is myFunctions.pyc.

 

 

 

 

 

return sends a result object back to the caller

 

When a function is called, the caller stops execution

until the function has finished and returns control to the caller.

 

Functions that compute a value send it back to the caller

with a return statement; the returned value

becomes the result of the function call.

 

All of our example functions so far have returned a value.

 

 

 

 

 

The return statement

 

The Python return statement can show up

anywhere in a function body;

it ends the function call and sends a result back to the caller.

 

 

 

 

 

 

The return statement is optional

 

The return statement is optional;

if it's not present,

the function ends at the last line in the function body. . .

 

def times(x):

    for i in range(1,11):

        print ("%d x %d = %d" % (i, x, i * x))

 

# see program 06-06.py

# of www.annedawson.net/python3programs.html

 

http://www.annedawson.net/python3programs.html

 

 

 

 

A function can have many return statements

 

A Python function can contain several return statements.

In the case where a function can contains several return statements,

execution of the function ends at the first return statement encountered. . .

 

def division(x,y):

    if (y == 0):

        print ("division by zero not allowed")

    return

else:

    (" returning %f divided by %f " % (x, y))

    return x / y

 

# see program 06-07.py

# of www.annedawson.net/python3programs.html

 

 

 

 

 

 

The absent or empty return statement

 

 

If the return statement is absent from a function,

or it's executed on a line on its own,

then Python automatically returns the None object,

but it is generally ignored.

 

 

 

 

 

 

 

The None object

 

The None object is a Python value that represents null

- indicating that no value (object) was created.

 

None has a numerical value of zero,

thus evaluates to false in boolean expressions.

 

 

# see program 06-07.py

# of www.annedawson.net/python3programs.html

 

http://www.annedawson.net/python3programs.html

 

 

 

 

 

A function with no arguments

 

Functions defined without a parameter list are called with no arguments. . .

 

def greeting():

    print ("Hello out there!")

 

greeting()

greeting()

greeting()

 

# see program 06-08.py

# of www.annedawson.net/python3programs.html

 

http://www.annedawson.net/python3programs.html

 

 

 

 

 

 

A Boolean function

 

A Boolean function is one which returns either true or false.

The following example program includes a boolean function.

 

def isPositive(x):

    if (x >= 0):

        return 1 # 1 is true

    else:

        return 0 # 0 is false

 

# see program 06-09.py

# of www.annedawson.net/python3programs.html

 

http://www.annedawson.net/python3programs.html

 

 

 

 

 

 

 

A function can operate on objects of different types

 

As with everything else in Python, there are no type constraints on functions.

We can pass arguments of any type to a function and return any kind of object.

 

def doubleIt(x):

    return (2 * x)

 

y = 3

print (doubleIt(y))

z = "Spam "

print (doubleIt(z))

 

# see program 06-10.py

# of www.annedawson.net/python3programs.html













 

 

http://www.annedawson.net/python3programs.html

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

********************************************************