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
Indefinite iteration - where the number of times the loop is executed depends on how many times a condition is met.
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>
for keyword indicates the start of a for loop.
temporary variable represents the value of the element in the collection the loop is currently on
in keyword separates the temporary variable from the collection used for iteration
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)
When you run the program, the output will be:
milk
eggs
cheese
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>
example:
count = 0
while count <= 5:
print(count)
count += 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 oneWhen 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.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
Here is a diagram to help visualize a while loop
Top comments (0)