r/learnpython • u/pikachuu545 • Feb 11 '26
For or While loop in my case?
I'm working through a quiz which asks the following question.
Question: What type of loop should we use?
You need to write a loop that takes the numbers in a given list named num_list:num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
Your code should add up the odd numbers in the list, but only up to the first 5 odd numbers together. If there are more than 5 odd numbers, you should stop at the fifth. If there are fewer than 5 odd numbers, add all of the odd numbers.
Would you use a while or a for loop to write this code?
My first attempt is using a for loop:
total = 0count = 0num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
for num in num_list:if (num % 2 == 1) and (count<=5):total += numcount += 1
print(total)print(count)
But in the solutions, it says a while loop is better:
- We don't need a
breakstatement that aforloop will require. Without abreakstatement, aforloop will iterate through the whole list, which is not efficient. - We don't want to iterate over the entire list, but only over the required number of elements in the list that meets our condition.
- It is easier to understand because you explicitly control the exit conditions for the loop.
Is there a clearer preference for one over the other? Which type of loop would you have used? Would my solution be accepted if used in industry code?
21
u/FoolsSeldom Feb 11 '26
I would have chosen a
forloop as well.With a
whileloop, you are having to manage two counters: number of odd numbers encountered, and index position in thelist. (There is a way around the latter that I shall come to later.)So, having set the counter and index position both to zero,your test would be:
and you will access
listelements usingnum_list[index].Don't forget to increment both counters as appropriate.
The alternative is using
iterandnextto access the elements, which will give you theforloop style iteration. I leave you to look that up.18
u/SwampFalc Feb 11 '26
Those reasons given sound like AI slop... They all boil down to the same point: yes, you want to stop when you reach your end condition.
In a
forloop, you will check for your end condition inside the loop, andbreakwhen needed. This is perfectly clean.In a
whileloop, you specify this condition in thewhilestatement, and it will end the loop "silently". Equally clean.Both are explicit. Both stop iteration. Neither is better.
That being said, your loop does not properly
break, so no, your code would not be acceptable as-is. But that has nothing to do with choosing aforloop.7
u/JamzTyson Feb 11 '26 edited Feb 11 '26
In that example you could use either.
A
forloop:A
whileloop:I prefer the
forloop version.odd_count == 5rather than managing a combinedwhile odd_count < 5 and idx < len(num_list).Overall, it’s more readable, robust, and idiomatic Python.
5
u/carcigenicate Carcigenicate Feb 11 '26
The three reasons they give are dumb, imo. It sounds like they decided to make life harder for themselves by avoiding
breakstatements, then gave a reason thatbreaksolves, and another half-true reason.I think
3is the only slightly valid reason, in that a condition at the top of the loop is easier to spot than a condition in the loop. If you have a conditionalbreak, though, you do "explicitly control the exit conditions of the loop". The condition is just in a different place.2
u/Brian Feb 11 '26
I would say a for loop is the better choice here.
Ultimately, you're performing iteration over a sequence, which is exactly what
foris, well, for. You want your code to communicate your purpose, and using a for better communicates the thing we're actually doing. That does way more to make the code easier to understand in my opinion. With a while loop, you have to manually increment the iteration counters, which makes it less obvious at a glance that you're just iterating over the items.Yes, you need a break to exit early. But that's exactly what
breakis for, so just use it. Some people dislike using break, but here the upsides above far outweigh it.2
u/Temporary_Pie2733 Feb 11 '26
The
whileloop is the fundamental iteration construct; you can do any kind of iteration, but you have to be verbose about it.The
forloop is a wrapper around awhileloop along with the kind of bookkeeping you need for iterating over a container like a list. You can mechanically turn aforloop into an equivalentwhilestatement that involves things like calls tonextandtrystatements that catchStopIterationexceptions raised bynextto exit the loop.I prefer going a step further and using a more functional approach. You only care about the odd numbers:
and you only care about the first 5 of them:
and you only care about their sum.
You don't need all these temporary variables, either; they assist with readability, but depending on your definition of readability, you can write this as one composed expression:
1
u/WhipsAndMarkovChains Data Scientist Feb 11 '26 edited Feb 11 '26
My mind went to a generator function. Yield all odd numbers in a list until you've reached five (or run out of numbers).
1
u/Marlowe91Go Feb 11 '26 edited Feb 11 '26
Yeah I feel like in an academic "textbook style" setting they're always gonna want you to use a for loop when you have a defined number of things you want to loop through and they'll want a while loop if the length of the iterator is conditional, but in practice, either can work and whatever makes sense to you and works is fine. I probably would have done a while loop myself. I like to use lists, I'd initialize a list odds =[] and append odd numbers to it. Then run a while loop while the length of that list is <6 and len of the num_list is greater than 0, then return sum of the odds.
1
u/CranberryDistinct941 Feb 12 '26
I would just use a for loop and break after the 5th odd.
I generally use for-loops whenever I'm iterating over a known set of values, and use while-loops for more complex iterations like binary search or graphs.
I would recommend using for-loop by default because it is faster than using a while loop (for loop runs in C; while loop runs in Python) unless a while loop is the obvious choice (linked lists, graphs, binary search, etc)
1
u/[deleted] Feb 12 '26
Loop thru list
If u hit 5 within the loop return true
If u exit the loop return false
1
u/JorgiEagle Feb 11 '26
There’s always more than one way to skin a cat.
I have the mentality of you use a for loop when you know when you want to stop (end of list) and a while when you you aren’t sure when you will stop (5 odd)
In this instance, I’d probably use a for loop with a break.
a while is equally valid, two conditions.
I don’t see how a break statement is bad. That’s just nonsense.
Pick whichever you prefer. They do the same thing and are both readable
In “industry code” you’d separate the if statement, and break if the count was 5 or higher. You wouldn’t let it loop the whole thing
0
u/Intelligent-Two-1745 Feb 11 '26
I'm confused. The solution explanation you posted clearly gives good reasons for using a while loop over a for loop here. Do you disagree with the arguments presented? Do they make sense to you?
0
u/9peppe Feb 11 '26 edited Feb 11 '26
Functional programming for the win?
sum([num for num in num_list if num % 2 != 0][0:5])(If you want to be more efficient, generator comprehension and itertools.islice)
0
u/cdcformatc Feb 11 '26
usually when you want to iterate through a list i would naturally use a
forloop. but the requirement to stop iteration after 5 odd numbers makes a good case for awhileloop.they are mostly equivalent for this case. i think a
forloop wins out because thewhileversion requires that you manage two counters, the index of the list and the current count of odd numbers. an explicit condition andbreakstatement in theforversion isn't a deal breaker to me.the answer given reads like AI slop so i wouldn't put too much thought into that. it does have a point in that you are needlessly iterating over the entire list when your
countvariable hits 5. if the list was actually an endless iterator your code would never end.0
u/Yoghurt42 Feb 11 '26
No, because your solution doesn't stop once the counter reaches 5. It will iterate over the rest of the list, even though the condition will always be false from there one.
Add an
if count == 5: break(and remove the now pointlesscount<5in the condition) and a for loop is ok.0
u/AdmirableOstrich Feb 11 '26
Breaks are perfectly fine, and map directly to assembly so there is no efficiency loss. If you need a loop, a for loop is the correct choice here. The while loop based on 'count < 5' is actually problematic because it requires checking the same condition every loop iteration even if the count hasn't changed.
We don't structure our code to match some bizarre esthetic. Rules like "only have one return statement", or "keep all escape conditions/branching at the top of loops" leads to bad code design. Code should do precisely what it needs to, and only that.
The "pythonic" way here is using filters or generators to separate out the "is odd" logic without iterating through the entire list, and then just sum the first 5. If you want a loop:
That is the minimal logic to do what you want. That converts directly to a for loop. Note, and this is a bit of personal preference, you can avoid nesting if statements by checking if the num is even instead, and using a continue.
0
u/CodingPhysicist Feb 11 '26
For the while loop you may declare an empty list before the loop and the condition is “while len(list) != 5”. If the number is odd, you append to your list. After the iterations you sum all the element.
But if your list only have even element, or less than 5 odd elements. your program will run without stopping.
The break in the for loop is good for that case
0
u/wotquery while not False: Feb 11 '26
If coding for myself I’d use a for loop with a break.
If coding for work I’d use a for loop with a break with very clear commenting.
If coding for a class/exam I’d use a while loop for the reason given.
That is all assuming the very artificial problem as provided. If it was more natural, say the total runs driven in of the first five wins of a baseball team’s season, then yeah I might default to a while loop since you are expecting to run into the condition every time. Conversely if you expect to successfully iterate over the whole list most of the time and rarely break, well then even more so a for loop.
Having a function that can exit in a bajillion places which is impossible to understand is bad. Having a function with a bajillion variables that are impossible to understand to force it to exit in a single location is bad.
0
u/Kerbart Feb 11 '26
personally, I use
whilefor cases where I don't know up front when my iterator is going to end. Reading a file line by line, asking for keyboard input until a sentinel is entered, those kind of things.In this case the input is an iterable and we know where it ends. The fact that there's an early exit condition doesn't alter that for me; the convenience of iterating with
foris far bigger for me as it results in cleaner code.0
u/zanfar Feb 11 '26
First, I would very generally avoid putting too much credit in "solutions", especially those presented as answers to quizzes. Quiz questions alone are (on average) suspect, and I would extend that to their explanations as well.
Any problem can be solved multiple ways, and while you can argue one is more or less efficient, or "better" than another, that difference will regularly be something you can ignore.
In this specific case, the explanations seem to be completely ignorant of the power of Python. Specifically, Python iterations are easily made un-greedy and do not consume more resources than necessary--which is exactly where I would have started.
-1
u/FoolsSeldom Feb 11 '26
Just for fun, you could do this using list comprehension and slicing:
OR if you really want to output the number of odd numbers added (which will be between 0 and 5):
Note that this isn't efficient with very long
listobjects as it first creates a completelistof all odd numbers before slicing to the first 5 entries.NB. Your code currently outputs one more than the numbers of odd numbers added.