I cant understand why ps1a_solution.py uses a while loop instead of a for loop. I used the later for my script but got confused when I saw the solution. Are there any benefits of a while loop?
For loops are actually while loops that go a known number of iterations. If the number of iterations isn't known when the loop starts, a for loop, unless endless, isn't very suitable. While loops keep going until their condition is met. If that problem is the 10000 prime, and you're storing the primes in a list named primes: while( len( primes ) < 10000 ): #find more primes!
Thanks for the answer! However this time the number of needed loops were known. The number of months in a year. My question is more about the pro's and con's. Both scripts produced the same result but I used a for loop and I'm more or less wondering if I should have gone with a while loop anyway. I used: for i in range(1, 13): #Do this The solution included: numMonths = 1 while numMonts <= 12: #Do this numMonths += 1
In this situation I would likely go with the for loop but it also doesn't make a lot of difference. I would also suspect the timing would be identical even at large numbers. As mentioned above, For is "Syntactic Sugar" for While in most languages and in a compiled language would likely compile to the same byte code.
I was also initially confused by this. I think the while loop with a while True condition is basically simpler to code, because you just use a definite break statement instead of calculating the proper termination conditions to make a for loop. However, friendly neighbourhood programmers have agreed with my gut feeling that it's not a very elegant solution. Also, you have to make very certain that the break statement will always execute eventually. I think it's confusing here because the course hasn't discussed using a whileTrue loop (unless I missed something?), and so they'd really do better not to use it.
The problemset was handed out during session 2 and was due session 4. For loops were introduced in session 3 so that might be a reason for Guttag using a while loop.
Join our real-time social learning platform and learn together with your friends!