[Tutor] Re Help with this script

Alan Gauld alan.gauld at freenet.co.uk
Thu Apr 28 09:10:12 CEST 2005


> OK Alan, I thing I have seen the light!!.

Almost. :-)

> --------------------------------------------------------------------
-----
> def print_options():
>        print "------------------------------"
>        print "Options:"
>        print "a. print options"
>        print "f. quit the programme"
>        print "------------------------------"
>
> print_options()
> choice = 0
> while choice != 'f':
>     print
>     choice = raw_input("Choose an option: ")
>     if choice == 'a':
>         print "Here we go again"
>         print_options()
>     if choice == 'f': break

That should be all you need.

> print_options()

This shouldn't be needed.

> Is it that if you use "while 1:" you create a recursive function?
Hope I am
> right.

NO the recursive bit is where the function calls itself.
In the previous version you had the while loop inside
the function so that you called print_options while you
were still inside print_options, like this:

def print_options():
       print "------------------------------"
       print "Options:"
       print "a. print options"
       print "f. quit the programme"
       print "------------------------------"
    choice = 0
    while choice != 'f':
      print
      choice = raw_input("Choose an option: ")
      if choice == 'a':
          print "Here we go again"
          print_options()  ## THIS CALL IS INSIDE THE FUNCTION
      if choice == 'f': break

It was the fact that the call was inside the function that made
it recursive. When you selected f to quit you simply quit that
call to the function and returned to the higher level call and
had to select f again until you eventually got back to the top
level.. I'll try to draw it:

print_options()
    choice = a
    print_options()
       choice = a
       print_options()
         choice = a
         print_options()
            choice = f
         choice = f
       choice = f
    choice = f
exit

You needed to select f to exit each call to print_options.

Any clearer?

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list