[tutor] functions and classes

Magnus Lycka magnus@thinkware.se
Wed Oct 23 17:47:02 2002


At 09:51 2002-10-23 -0600, Dan Dud wrote:
>def compare(x,y): # this is what I think the compare should look like
>    if x < y:
>        print x, "is less then", y
>    elif x > y:
>        print x, "is greater then", y
>    else:
>        print x, "and", y, "are equal"

This obviously works. A shorter version could be:

def compare(x,y):
     print ["%s is less than %s", "%s and %s are equal",
            "%s is greater than %s"][cmp(x,y)+1] % (x,y)

The builtin function cmp(x,y) returns -1, 0 or 1 depending
on whether x < y, x =3D=3D y or x > y.

>def disbatch(choice): # this is what I think the disbatch should look like
>    if choice =3D=3D 'A':
>        functionA()
>    elif choice =3D=3D 'B':
>        functionB()
>    elif choice =3D=3D 'C':
>        functionC()
>    else:
>        print "Invlaid choice"

It looks like this could work as well. Also this could use
the pythonic strength in datatypes instead of an if statement:

def dispatch(choice):
     try:
         {'A': functionA, 'B': functionB, 'C': functionC}[choice]()
     except KeyError:
         print "Invalid choice"

This is the same thing, just shorter.

>the next question is When I define a class do I import these then use them=
=20
>by calling them then define the class or do I do that afterwards
>thanks for the everyone help

You use import when you want to use code in another file a.k.a. module.
Whether you import these or not depends on your choice of program
structure.

Python is a multi-paradigm language just like C++. You don't need to
have classes. It's difficult to say how you should organize your
code when we don't know what you are trying to accomplish. Take one
step at a time, and it will probably work out.

It requires a certain skill to be able to program in very small
steps, and to always have working code that grows line by line.
But it's still a good choice. If you write more than ten lines
of code with your code in a state of flux, you get lost. At least
if you are as confused as I am.



--=20
Magnus Lyck=E5, Thinkware AB
=C4lvans v=E4g 99, SE-907 50 UME=C5
tel: 070-582 80 65, fax: 070-612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se