Department of Mathematics, Computer Science, and
                Statistics
St.
                Lawrence University
Zonohedron
 

What is this object?

...

Links
Overview
Schedule
Grading Info
Class Notes

 

CS 140: Introduction to Computer Programming


Defining Functions

Just as with the functions you probably remember from your math classes, a function in programming is a block of code that takes one or more inputs, does something with them, and then (usually) returns a value of some sort.  The basic format looks like this.

def block(letter):
    print letter*3
    print letter*3


This function takes a string (presumably a single character) and then prints a block of this letter; two rows of three letters each.  So including the line block("c") within your program will result in a block of c's being printed to the screen.  Or one could "blockify" an entire word by typing

word = raw_input("Enter a word: ")
for letter in word:
    block(letter)


For the record, function definitions usually appear at the start of a program.

Functions usually return a value based on the inputs.  For instance, we could define a function that counted the number of times we can divide a given number by 3 before dropping below 1 as follows.

def divbythree(value):
    count = 0
    while value >= 1:
        value = value/3
        count = count + 1
    return count


The return command sends the output back to the main program.  So we are now able to very efficiently check whether a particular number can be divided by 3 exactly twice within a program by typing  if divbythree(number) == 2:, for instance.  This is one of the main advantages of implementing functions within a program—it often results in code that is both more efficient and more readable.

As a final illustration, let's define a function that takes two inputs, an interest rate and a yearly contribution, and determines how much money will accrue over a forty year span in an account that adds interest once a year just before a new contribution is made.

def value(contrib,rate):
    total = 0
    for j in range(0,40):
        interest = float(total)*rate/100
        total = total + interest + contrib
    return total


We could now neatly make a chart of account values based on various interest rates and annual contributions using just a few lines of code.

for j in range(1000,10000,1000):
    for k in range(2,7):
        print value(j,k),
    print


This is another big advantage of using functions; namely, better organized programs.