for or while loop to do something n times

前端 未结 3 994
失恋的感觉
失恋的感觉 2020-12-16 09:12

In Python you have two fine ways to repeat some action more than once. One of them is while loop and the other - for loop. So let\'s have a look on

相关标签:
3条回答
  • 2020-12-16 09:43

    The fundamental difference in most programming languages is that unless the unexpected happens a for loop will always repeat n times or until a break statement, (which may be conditional), is met then finish with a while loop it may repeat 0 times, 1, more or even forever, depending on a given condition which must be true at the start of each loop for it to execute and always false on exiting the loop, (for completeness a do ... while loop, (or repeat until), for languages that have it, always executes at least once and does not guarantee the condition on the first execution).

    It is worth noting that in Python a for or while statement can have break, continue and else statements where:

    • break - terminates the loop
    • continue - moves on to the next time around the loop without executing following code this time around
    • else - is executed if the loop completed without any break statements being executed.

    N.B. In the now unsupported Python 2 range produced a list of integers but you could use xrange to use an iterator. In Python 3 range returns an iterator.

    So the answer to your question is 'it all depends on what you are trying to do'!

    0 讨论(0)
  • 2020-12-16 09:53

    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()
    
    0 讨论(0)
  • 2020-12-16 09:56

    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)).

    0 讨论(0)
提交回复
热议问题