Repetition

--Originally published at Python

In this post I will be talking about repetition in Python 3 and when you should use which type of repetition. As we already know (or should) the 2 types of repetition we have are “while” and “for”. They are different but follow the same idea, a process is repeated depending on what you want to achieve.

While is better used when you don’t know the number of times a process will be repeated. That’s why you just state a condition and expect it to be false at some point in time, that’s when it will stop and you will get your result from it.

For is used when you have a List or a Tuple. We know how many times a process will be repeated because we know the number of variables inside of the list or tuple used. So the final answer here will depend on the number of variables you have stored, not on a condition given to the program.

In conclusion, use While when you want a loop to repeat infinitely until a certain condition is false, use For when you have a list or a Tuple and you want a process to be repeated according to the number of variables you have in them and their value. If you want another explanation and easy to follow examples, click here.