+ 2
What do you think about this while to for convertion methods?
So my teacher said "All for loops are convertible to while, but not all while loops are convertible to for" I completely understand why that is, and even more from the way python's for-loop works I came up with some "methods" that could be used to convert all while loops to for loops, I don't recommend them for real code But what do you think about educational purposes and such things like training? Would it be a good way to make someone learn things? https://code.sololearn.com/cK8vh2gY44uJ/?ref=app
10 Answers
+ 5
there is one way to do an infinitely loop within a for loop. see the code and the comments:
https://code.sololearn.com/cPJ66I6W7eAG/?ref=app
+ 2
The generator solution is interesting actually. It could bridge the gap pretty well. But as you mentioned yourself, they both have there strengths.
The first approach were you append to the list from whiting a for each loop, was shocking to me (transitioned to Python from Java). That won't work with a compiled language. And also, the list might grow infinitely causing a stackoverflow (won't happen with the python interpretor, but it will crash).
+ 2
Simon Sauter đ€đ€đ€đ€ I give up. Python is being python.đ€·
+ 2
Lothar Yeah, true. A circular iterator makes sense. It won't fill up the stack either.
+ 1
Simon Sauter Actually, that might happen. Given that you can mutade the list from within the for each loop, as long as you pop out the first element each time, the list won't grow and the loop can go on forever. It's just a very costly way of doing a while loop.
+ 1
Lothar the last thing with the cycle is pretty useful to know, I also thought of another way to make an infinite loop without libraries, I'll test it and if it works I'll add it here
0
I think I remember someone accidentally creating an infinite loop using the first method here on sololearn once.
0
Simon Sauter Nope. That didn't work. The for each loop is iterating through the list and expecting an item at the next index. So popping the previous item out will just end the loop. As the item added to the list will replace it and won't be used in the next iteration.
Python is just weird.
0
True, it's not really infinite because lists cannot be infinitely long.
Interestingly, if you try doing this with a dictionary instead of a list it causes a runtime error. Neither changing the length of the dictionary nor changing its keys is allowed while iterating over it.
0
I tried and I made the generator function in an object so it can be used without a global
https://code.sololearn.com/cc1kQLU7tTy8/?ref=app