kster

kster

Posted on September 21, 2022

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

💖 💪 🙅 🚩
kster
kster

Posted on September 21, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Python Loops
python Python Loops

September 21, 2022