while within while

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Oct 27 21:33:54 EDT 2007


On Sat, 27 Oct 2007 15:11:37 -0400, Shawn Minisall wrote:

> I've been having some problems with using a while statement for one menu
> within another while statement for the main menu, first time I've done
> it.  

[snip]

> def main():

[and snip masses and masses of code]

The first thing you should do is break your program up into functions 
rather than putting everything into one massive lump of code.

I know some people who, once they reach ten lines of code, break it up 
into a separate function. That's possibly a little extreme, but at the 
very least you should split each logical group of code into its own 
function. For example, your main() function might look something vaguely 
like this:


def main():
    initialize()
    welcome()
    finished = False
    while not finished:
        finished = play_game()
    goodbye()


Notice that there's only one while loop. That's because the inner while 
loop is inside the play_game() function.

Perhaps the biggest reason for splitting your code into functions is that 
it allows you to isolate each logical task as a separate piece of code, 
write it, test and debug it in isolation.


-- 
Steven



More information about the Python-list mailing list