I have a while loop:
def setWorkDays(dayNameList):
workDays = []
while self.count > 0: #continue loop until all 5 work days have been filled or the loop breaks at the end
for day in dayNameList: #iterate over days, adding days to work days if they are not free days, AL days, preferred days, or free Saturdays
if day in self.freeDays or day in self.alDays or (day == 'Saturday' and self.satOff is True):
continue
elif day in self.programDays:
workDays.append(day)
self.count -= 1
elif self.preferredDay is not None and day in self.preferredDay:
continue
else:
workDays.append(day)
self.count -= 1
if self.preferredDay not in self.workDays: #if iteration completes, 5 work days have not been filled, and the preferred day has not been added, add the preferred day
workDays.append(self.preferredDay)
self.count -=1
return workDays
the idea behind the loop is that the second that self.count hits 0, the loop is terminated. This is the only function in which self.count is modified. Yet I’m getting strange results, where the loop appears to go on for at least 1 count too long, as the program is outputting -1 in some cases for self.count. Should this be happening? Shouldn’t the while loop terminate the second self.count hits zero, or does it have to first finish the for loop? Should I be adding conditional logic after the self.count decrements that checks if self.count is zero and breaks if it is? That seems like the purpose of the while loop …
A
whileloop doesn’t automatically exit in mid-loop as soon as its condition is no longer true; it just checks the condition at the start of each loop. If you want to get out early, you need tobreakexplicitly (or do something else non-local, likereturnfrom the function orraiseto anexcepthandler outside the loop).It seems like what you’re trying to do is get out of the
forloop early, ifself.countever hits 0. There’s really no way to do that directly. You have to check each time you decrement it.However, you really don’t need
self.countat all. You decrement it exactly in the same places youappendtoworkDays. So, just check whether you’ve got 5 of them yet. In other words, eachself.count -= 1becomes:There is actually a way to do what (I think) you want in Python: use a generator instead of a list. If you
yieldeach value instead of appending it to alistand then returning thatlistat the end, then you just stop iterating over the generator once you get 5 entries.For example:
Often, you don’t even really need the
list, all you need to do is iterate over it. For that, you could do:Or:
A lot of things that generators can do feel like magic until you understand them—which often means you shouldn’t do them until you learn about generators. So, if this makes no sense to you, don’t just pick it up and use it. But if it prompts you to learn how to write and use generator functions, great!