DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
kster
kster

Posted on • Updated on

Python Loops

First of all what is a loop? In programming a loop is a process of using an initialization, repetitions, and an ending conditions. In a loop, we perform a process of iteration (repeating tasks).

Programming languages like Python implement two types of iteration

  1. Indefinite iteration - where the number of times the loop is executed depends on how many times a condition is met.

  2. Definite iteration - where the number of times the loop will be executed is defined in advance

An example of a definite loop is a for loop
This is the general structure of a for loop

for <temporary variable> in <collection>:
<action>
Enter fullscreen mode Exit fullscreen mode
  1. for keyword indicates the start of a for loop.

  2. temporary variable represents the value of the element in the collection the loop is currently on

  3. in keyword separates the temporary variable from the collection used for iteration

  4. action to do anything on each iteration of the loop.

This is a for loop in action:

groceries = ["milk","eggs","cheese"]

for items in groceries:
print(groceries)
Enter fullscreen mode Exit fullscreen mode

When you run the program, the output will be:

milk
eggs
cheese
Enter fullscreen mode Exit fullscreen mode

A while loop is a form of indefinite iteration.
While loops perform a set of instructions as long as a given condition is true.

This is the structure

while <conditional statement>:
<action>
Enter fullscreen mode Exit fullscreen mode

example:

count = 0
while count <= 5:
print(count)
count += 1
Enter fullscreen mode Exit fullscreen mode
  1. count is initially defined with the value of 0. The conditional statement in a while loop is count <= 5, which is true at the initial iteration of the loop, so the loop executes.
    Inside the loop, count is printed and then incremented by one

  2. When the first iteration of the loop has finished Python returns to the top of the loop and checks the conditional again.
    Now the count would equal to 1 and since the the conditional still is true the loop continues.

  3. The loop will continue until the count variable becomes 5, and at that point, when the conditional is no longer True the loop will stop.

The output would be:

0
1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Here is a diagram to help visualize a while loop

diagram of a for loop

Top comments (0)

DEV has this feature:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. πŸ›