Python Forum

Full Version: Break for While and For
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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.
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)
(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 !!!