When to use what type of repetition in a program

--Originally published at Sierra's Blog

There are two types of repetitions in python: For and while.

For loops are used when you have the idea of how much times you need to repeat the code, while the while loop is used when you don’t have a single clue of how much time do you need to repeat it.

for loops will continue until a a variable reaches the desired number, for example:

for i in range(0,10):

print(“hi”)

this will print the word “hi”10 times because the value of the variable “i”will be i+1 every time the loop ends and the loop has the order to stop when the letter i becomes 10.

min = 10

max = 20

while min!=max:

print(“hi”)

min = min+1

max = max-1

the loop while will only stop when the statement min!=max becomes false. This will print the word “hi” 5 times.

As you can see, the while loops are used when the number of times that you need to repeat the code isn’t known by us.