Iteration, while loop, and for loop
Michael Selik
michael.selik at gmail.com
Tue Jun 28 09:51:54 EDT 2016
On Tue, Jun 28, 2016 at 9:26 AM Joseph Lee <joseph.lee22590 at gmail.com>
wrote:
>
> -----Original Message-----
> From: Michael Selik
> Sent: Tuesday, June 28, 2016 6:16 AM
>
> MS: You should not. Use the first version, it's much better. Python
> for-loops are preferable to while-loops.
>
> JL: For the most part, for loops are better, but there are times when
> while loops are preferable such as when you don't know the size of the
> input beforehand.
Not knowing the number of elements is not a reason to prefer a while-loop.
A for-loop handles that quite well.
with open('example.txt') as f:
for line in f:
print(line)
We often loop over files without knowing how big a file is.
More information about the Python-list
mailing list