Need help understanding this while loop
python - for or while loop to do something n times - Stack Overflow
[python] For loops vs while loops
Why would somebody use a loop construct when there is goto? Why would somebody use a high-level language when there is assembly language? Why would somebody name their variables when they can just use the memory addresses?
Answer: Because writing code that intuitively "looks like" the thing it is intended to do, both a) makes writing programs much less work, b) dramatically reduces the number of bugs, and c) greatly decreases the difficulty of reading, understanding, and maintaining the code later.
We use for loops when we want to loop over a range, or loop over the elements of a set. This is a fixed operation over a known amount of steps. Essentially, we are saying something along the lines of "for each employee, calculate the salary and submit a payment", so we call it "for" to highlight this relationship. In the case of Python, for loops also provide a special efficient syntax for looping over the elements of a set, so it's less work to type the thing in too. Some other languages call that variant of the for statement "foreach".
We use while loops when we want to continue repeating an operation while a condition continues to hold. For example, we continue looping as long as we encounter no errors, or as long as we receive more data from a network connection. These are not fixed ranges, but take place while a condition holds, so we call it "while".
More on reddit.comhow to restart while loop in python
Videos
but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?
That is what xrange(n) is for. It avoids creating a list of numbers, and instead just provides an iterator object.
In Python 3, xrange() was renamed to range() - if you want a list, you have to specifically request it via list(range(n)).
This is lighter weight than xrange (and the while loop) since it doesn't even need to create the int objects. It also works equally well in Python2 and Python3
from itertools import repeat
for i in repeat(None, 10):
do_sth()