[Tutor] recursive? [functions, main loop]

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat Sep 13 16:14:45 EDT 2003



> >        q=raw_input("Do you want try again?")
> >        if q == 'y':         #without ' ' you get error
[code cut]

> > that small silly program works but I would like to insert another
> > condition. after typing y after 'do you want try again?' how I can
> > start again all the program, asking again the three values?
>
> You can wrap your program in this kind of structure:
>
>  >>> while 1:
> ... 	q = raw_input("Do you want try again? (y/n)")
> ... 	if q == 'n':
> ... 		break
> ... 	# run your program here


Hello!


We can also wrap things a little more, by putting the core of our program
in a separate 'function'.  For example, the code below:

###
def main_loop():
    while 1:
        run_program()
        if raw_input("Try again? (y/n)") == 'n':
            break


def run_program():
    name = raw_input("Enter a name: ")
    print "Hello", name


main_loop()
###


shows how we can bundle things together in these functions.  It makes it
easier to call the whole bundled group by saying the single word
"run_program()".


Hope this helps!




More information about the Tutor mailing list