[Tutor] Question on Functions

Andrei Kulakov ak@silmarill.org
Wed, 03 Oct 2001 04:03:27 -0400

On Wed, Oct 03, 2001 at 01:12:21AM -0700, Josh Gregorio wrote:
> I am not sure I understand how to properly use functions (or when to use them). Suppose you had some code like this:
> x = 1
> y = 2
> def add(a,b):
>    c = a + b
>    print c
> add(x,y)
> print x,y
> Is there a way to store the result of a+b into a variable that is accessible outside of the function? Could you, for instance, add x and y, print the result c, and then update x to equal the result of x + y (from within a function)? 


def add(a, b):
    return a + b

result = add(x, y)

print result    # prints 3

In general, functions are used to package some repeating algorithm up.
Let's say you have this:

print "x + z is", x + z
print "y + a is", y + a
[100 more lines of the sort]

Now, you could make a function add() like the one above, to print the
result. In this case there's not much point to it because it's as easy to
type x + z as add(x, z), even easier. What if you had a function that
spanned 30 lines and you needed its output for different values in 100
places in your program? You could either write one 30 line function and
call it from 100 places (totalling 130 lines) or you could reproduce the
same logic on each of the 100 lines, giving you 100 * 30 - 3000 lines. One
problem here is that it's a lot more typing, another problem is that if
you want to change the function (like you found a bug or something), it's
much easier to change it in one places instead of changing it in 100

Typically, make a function if you see that there's a few places in your
program that use the same algorithm logic and you can save yourself typing
effort by using a function.

> Thank you,
> Josh 
> PS Could anyone recommend some good exercises to do to get more practice/understanding?

Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org