question

Wildemar Wildenburger lasses_weil at klapptsowieso.net
Tue Jan 22 15:48:01 EST 2008


Hi there :)

A little tip upfront: In the future you might want to come up with a 
more descriptive subject line. This will help readers decide early if 
they can possibly help or not.

jyoung79 at kc.rr.com wrote:
> def albumInfo(theBand):
>     def Rush():
>         return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres']
>         
>     def Enchant():
>         return ['A Blueprint of the World', 'Wounded', 'Time Lost']
>         
>     ...
> 
Yuck! ;)


> The only problem with the code above though is that I don't know how to call it, especially since if the user is entering a string, how would I convert that string into a function name?
While this is relatively easy, it is *waaayyy* too complicated an 
approach here, because . . .


> def albumInfo(theBand):
>     if theBand == 'Rush':
>         return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres']
>     elif theBand == 'Enchant':
>         return ['A Blueprint of the World', 'Wounded', 'Time Lost']
>     ...
>
. . . this is a lot more fitting for this problem.

You could also have used a dictionary here, but the above is better if 
you have a lot of lists, because only the one you use is created (I 
think . . .).

You might also want to consider preparing a textfile and reading it into 
a list (via lines = open("somefile.txt").readlines()) and then work with 
that so you don't have to hardcode it into the program. This however is 
somewhat advanced (if you're just starting out), so don't sweat it.



> I'm not familiar with how 'classes' work yet (still reading through my 'Core Python' book) but was curious if using a 'class' would be better suited for something like this?  Since the user could possibly choose from 100 or more choices, I'd like to come up with something that's efficient as well as easy to read in the code.  If anyone has time I'd love to hear your thoughts.
> 
Think of classes as "models of things and their behavior" (like an 
animal, a car or a robot). What you want is a simple "request->answer" 
style functionality, hence a function.


Hope that helps.
Happy coding :)

/W



More information about the Python-list mailing list