User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 423,433 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 4,654 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser: Programming Forums

Starting Python

Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,466
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 10
Solved Threads: 176
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Re: Starting Python

  #138  
May 18th, 2008
Easy ways to break out of nested loops came up in the forum, so I played with it a little. Using break will only get you out its associated loop like this example shows ...
  1. w = h = d = 10 # for testing
  2. for x in range(0, w):
  3. for y in range(0, h):
  4. for z in range(0, d):
  5. print x, y, z
  6. stop = raw_input("Stop? y/n")
  7. # alas this will only break out of the z loop
  8. if stop == "y":
  9. break
One solution would be to put the nested loops into a function and use return to break out ...
  1. def nested_loop():
  2. """use of return to exit a nested loop"""
  3. w = h = d = 10 # for testing
  4. for x in range(0, w):
  5. for y in range(0, h):
  6. for z in range(0, d):
  7. print x, y, z
  8. stop = raw_input("Stop? y/n")
  9. if stop == "y":
  10. return
  11.  
  12. nested_loop()
You can also raise an exception to get out ...
  1. # use of try/except to exit a nested loop
  2. w = h = d = 10 # for testing
  3. try:
  4. for x in range(0, w):
  5. for y in range(0, h):
  6. for z in range(0, d):
  7. print x, y, z
  8. if raw_input("Stop? y/n") == "y":
  9. raise StopIteration()
  10. except StopIteration:
  11. pass
May 'the Google' be with you!
Reply With Quote  
All times are GMT -4. The time now is 2:11 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC