Python Forum
Break for While and For
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Break for While and For
#1
Hello folks ;
I have a small question .
How can I apply "break" for "while " loop but if I have a for loop too ? Here is the example
       while True:
            random.randint()
#I compute something else here ,but accordingly I might generate new random values
            for k in range(self.p.T):
                for l in range (self.p.N):
                    if self.Itm[k][l]<0:
                        print("negative quantity, generate random periods again")
else:
break 
Until I have positive quantity I want to generate new random values but my break does not work properly since I have for loop for checking quantity.
Can you give some ideas to correct the code? Thank you
Reply
#2
To my knowledge, there is no way in Python to break an outer loop. The keyword always applies to the current loop you're working in. You'll have to (1) reorganize the code to change the while loop to a for loop or change your condition to a logical test or (2) place your while loop inside a function on its own and use return to terminate the function.
Reply
#3
Not tested but something like

while True:
    random.randint()
    #I compute something else here ,but accordingly I might generate new random values
    if any(self.Itm[k][l]<0
           for k in range(self.p.T)
           for l in range (self.p.N)):
        print("negative quantity, generate random periods again")
    else:
        break
There might be better solution but without seeing rest of the code is difficult to say (i.e. I don't like this double for in the comprehension expression)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
(Oct-16-2018, 11:43 AM)buran Wrote: Not tested but something like
while True: random.randint() #I compute something else here ,but accordingly I might generate new random values if any(self.Itm[k][l]<0 for k in range(self.p.T) for l in range (self.p.N)): print("negative quantity, generate random periods again") else: break
There might be better solution but without seeing rest of the code is difficult to say (i.e. I don't like this double for in the comprehension expression)
Thank you Buran , it worked !!!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020