[Tutor] Best Practice: Subroutines and Loop logic

Alan Gauld alan.gauld at btinternet.com
Fri Sep 4 02:09:31 CEST 2009


"GoodPotatoes" <goodpotatoes at yahoo.com> wrote

> #logic loop
> for word in lData:
>    if word in lWords:
>        continue
>    elif sub1(word)[0]=1:
>        word=sub1(word)[1]  # <--- Here is my question.
>    else:
>        print word " not found.\n"
>
> The subroutine is being run once at the elif statement.
> I don't want to run it again just to get the [1] value.
>    *Is there any way to capture all of the values returned when it is run 
> during the elif statement?

Yes but you need to call it before the if.

> #logic loop
> for word in lData:
       test, wrd = sub1(word)
>    if word in lWords:
>        continue
>    elif test ==1:
>        word=wrd  # <--- Here is my question.
>    else:
>        print word " not found.\n"

>    *Is this actually running twice?

Yes, your code called sub1 twice.
But my code has the disadvantage of now calling sub1 once for every
word in IData. We can avoid that by inverting the if test:

> for word in lData:

>    if word not in lWords:
>         test, wrd = sub1(word)
>         if test ==1:
>                 word=wrd
>        else:
>            print word " not found.\n"

That only calls sub1 when needed and only does it once even then

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list