[Tutor] More Function Questions (Joseph Q.)

Jacob S. keridee at jayco.net
Sun Apr 17 19:08:59 CEST 2005


> Hi all,
> Another function question.....
>
> def bar(x, y):
> return x + y
>
> bar(4, 5)
>
> So I can put anything I want in there. What good is a function like that?

Alright, so what good is this function?

def bar(x,y,z):   ##Where in this case x, y, and z are strings
    return x+z+y

>>> bar("a","b","-")
'a-b'
>>> bar("1","2","< + >")
'1< + >2'

And, what good is this function?

def bar(x,y):
    return x+y-x*y

>>> bar(1,2)
1
>>> bar(5,7)
-13
>>> bar(1,4)
1

Nothing, apparently, right?  Okay, so you got us, they're just examples. 
But that's what programming is all about.  Taking examples of functions that 
people or tutorials give you and elaborating on them until you can come up 
with your own that do what *you* want.

> Of course I know about.
> def foo():
> print "Hello all you who subscribe to the Python Tutor mailing list!"
>
> So what do you use the
> def bar(x, y):
> return x + y
>
> bar(4, 5)

Not to go against my grain of these are totally useless, but they aren't 
exactly.  Say you don't want to implement the operator module, or you want a 
slightly different effect.

def add(x,y):
    return x+y
def sub(x,y):
    return x-y
def mul(x,y):
    return x*y
def div(x,y):
    return float(x)/y  ## The float is to overcome the integer division 
default

di = {'add':add,
        'sub:sub,
        'mul':mul,
        'div':div}

ask = input("What is the first number? ")
ask2 = input("What is the second number? ")
funct = raw_input("What do you want to do to them? ")
if funct in di:
    print di[funct](ask,ask2)

Again, this may not seem useful now, but with more difficult functions that 
do many more manipulations to the arguments, etc., this is a actually a 
really useful coding technique.

I'm sure other members of this list will help further, so goodbye.
Jacob 



More information about the Tutor mailing list