Break for While and For - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: Break for While and For (/thread-13455.html) |
Break for While and For - juniorcoder - Oct-16-2018 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: breakUntil 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 RE: Break for While and For - stullis - Oct-16-2018 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. RE: Break for While and For - buran - Oct-16-2018 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: breakThere 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) RE: Break for While and For - juniorcoder - Oct-16-2018 (Oct-16-2018, 11:43 AM)buran Wrote: Not tested but something likeThank you Buran , it worked !!!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: breakThere 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) |