DEV Community

Elizabeth Njoroge
Elizabeth Njoroge

Posted on

Stop repeating yourself, try Loops.

Loops for repetitive tasks.

Loop takes a collection of items and run it once for each item. For example;

The output,

If you want to use a sequence of numbers making it to produce numbers one at a time ten we use range. It starts at 0 and stops before the number.


This prints 0,1,2, and does not include 3 since we start with 0.
If you want to choose where to start then range(start, stop). This starts at 2 and stops before 6 _so it stops at _5.

If you want to skip a number then range(start, stop, step). This skips number 2.

Loop over a string.
This gets you a character one at a time and used to count letters or even check for spellings.
Example with printing each letter,

Example with printing each letter with its position number,

Example with counting the vowels of the word,

Example with reversing the word,

Loops over a dictionary
Dictionaries store data in key: value
Example, we have a data on different animals and the number of legs they have;
animals = {"zebra": 4, "eagle": 2, "octopus": 8}

1.loop over keys, shows the keys(animals listed)

2.loop over values, shows only the values (number of legs)

3.loop over the keys and values (shows both the animals and the number of legs they have).

4.loop with position number (shows the position, the animal and the number of legs). We also use the enumerate to show position.

5.loop over multiple lists, uses two related lists to loop them together at once by using zip.

Example with three lists at once,

If one list is shorter, the extra is ignored,

Nested loops is a loop inside another loop and is common for grinds and table.

1.While in loops is used when there is a condition. You use this when you do not know in advance the number of iterations. If a condition is true the loops run unless the condition becomes false.

2.Break in loop leaves the loop early.

3.Continue in loop skips the rest of the current iteration and jumps back to the top of the loop.

4.Pass does nothing and means that it is intentionally empty.

Conclusion

  • For loops go through an item one by one.
  • Range stops before the last number.
  • Enumerate gives you index and value.
  • Zip uses two related lists to loop them together at once.
  • Pass does nothing.

Top comments (0)