When to use which repetition

So far we have seen both “while” and “for” loops, but now we will learn to judge in which situation we need to use either of them.

The “while” loop will repeat itself as long as the condition that accompanies it remains true, this means that a “while” loop will tend to repeat itself to infinity unless we do something to make the condition that controls it become false.

On the contrary, the “for” loop will tend to run once for each value given, and since we tend to have a finite amount of values to work with the loop tends to be finite as well.

Knowing this difference will save you a lot of work if you learn to differentiate the problem you need to solve.

A very easy way to identify which form of loop to use is reading the contents of the rest of the programs. Most of the time, if we are using lists, ranges, tuples or dictionaries we will be required to use a “for” loop, since the problem at hand is to go through all of the contents of either of the previously stated types and perform an action according to its contents and their value.

As for “while” loops, they come in handy when the amount of cycles we will have to perform in order to solve the problem is unknown to us.

You can even use both at the same time, as I implied earlier, it all depends on your needs.

One example of this is the case of having a list with vive values inside of it, all integers. We need to calculate the factorial of each number. To go over all of the length of the list and check all of the values we need to use a “for” loop, but to actually calculate the factorial we would need a “while” using the value found by the “for” to do the math, then the “for” would move on to the next position and so on.

And just like with the “if, elif, else” business, be warry of indentation.

Publicado por: juansalvadorfernandez

Elegí estudiar ITE porque pienso que es una carrera versátil con la que se pueden lograr cosas muy interesantes. Aunque realmente no sé si alguna otra carrera me gustaría más, las personas terminan haciendo lo que les gusta, independientemente de la carrera que estudien. Si alguien me pregunta quien es mi héroe, sería mi padre, pues es una persona fuerte que en momento de necesidad sacó adelante a su familia, pagó los estudios de sus hermanos, es un profesionista que disfruta de su trabajo y que tiene metas fijas y aspira a ellas con todas sus fuerzas. Hace tiempo tocaba la flauta dulce e intenté aprender a tocar piano, teclado y guitarra. No me gusta el deporte. Realmente no tengo un autor ni un libro favorito, siento que me falta encontrar un tema o un estilo que realmente me guste.

Etiquetas, Deja un comentario

Deja un comentario