[Tutor] while with function

Magnus Lycka magnus@thinkware.se
Mon Nov 18 05:39:03 2002


At 22:50 2002-11-17 -0500, fleet@teachout.org wrote:
>def add()
>     s_name=raw_input("Surname: ")
>     # several more lines of the same
>     y=1
>     while y>0:
>        get_list()
>
>def get_list()
>    print "1. Surname: "+s_name
>    # several more lines of the same
>    # read option while loop here
>
>I had to add "global s_name, ..., ..., etc." to add() in order to get
>get_list() to display the variables.  I tried moving the definition of
>get_list() ahead of the add() definition; but that made no difference.
>
>add(), of course, is called by main_menu().
>
>Is making the add() variables global the proper solution here?

Depends on what you mean by "proper solution", but no, I think
that's bad programming style. The obvious solution here is to
pass s_name and what ever other variables you need get_list to
be aware of as parameters. If something in get_list() changes y,
then it should return y. That shouldn't be global either. I.e:

def add():
     s_name = ...
     ...
     y = 1
     while y>0:
         y = get_list(s_name, ...)


def get_list(s_name, ...):
     print ...
     ...
     return whatever_becomes_y

If you know that y will be exactly 0 when it's time
to quit, replace "while y > 0:" with "while y:"

A shorter version would be...

def add():
     s_name = ...
     ...
     while get_list(s_name, ...):
         pass

...since you don't seem to use y for anything but
the loop control in add().


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se