Introduction

Similar to the while loop, the for loop is an iteration statement in programming language that permits a code block to be repeated a predetermined number of times. There aren't many computer languages that don't include for loops, but they come in a variety of flavors, meaning that each programming language has a different syntax and semantics.

Syntax of the For Loop

A for loop based on an iterator is the Python for loop. It iteratively traverses the elements of lists, tuples, strings, dictionary keys, and other iterables. The word "for" precedes the name of an arbitrary variable in the Python for loop, which will retain the values of the subsequent sequence object that is iterated over. The basic syntax is as follows:

for <variable> in <sequence>:
    <statements>
else:
    <statements>

The sequence object's elements are assigned one by one to the loop variable, or more precisely, the variable is set to point to the items. The body of the loop is run for each item.

A simple Python for loop illustration

languages = ["C", "C++", "Perl", "Python"]
for language in languages:
    print(language)

OUTPUT:

C
C++
Perl
Python

The for loop will be terminated and the programme flow will continue with the first line after the for loop, if any, if a break statement has to be performed in the for loop's programme flow. Break statements are often included in conditional statements, for example.

edibles = ["bacon", "spam", "eggs", "nuts"]
for food in edibles:
    if food == "spam":
        print("No more spam please!")
        break
    print("Great, delicious " + food)
else:
    print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")

OUTPUT:

Great, delicious bacon
No more spam please!
Finally, I finished stuffing myself

Taking "spam" out of our list of foods will have the following result:

$ python for.py
Great, delicious bacon
Great, delicious eggs
Great, delicious nuts
I am so glad: No spam!
Finally, I finished stuffing myself

Perhaps our dislike of spam is not as strong as our desire to quit eating other foods. This now activates the continue statement. When we hit a spam item in the script below, we use the continue statement to continue with our list of edibles. So keep going to stop us from consuming spam!

edibles = ["bacon", "spam", "eggs","nuts"]
for food in edibles:
    if food == "spam":
        print("No more spam please!")
        continue
    print("Great, delicious " + food)

print("Finally, I finished stuffing myself")

OUTPUT:

Great, delicious bacon
No more spam please!
Great, delicious eggs
Great, delicious nuts
Finally, I finished stuffing myself

write your code here: Coding Playground

The range() Function

The best way to repeatedly iterate through a list of integers is the built-in function range(). It produces an iterator of mathematical progressions, such as: Example:

range(5)

OUTPUT:

range(0, 5)

This result does not make sense on its own. It is a thing that can generate numbers ranging from 0 to 4. You will understand what is meant by this when we use it in a for loop:

for i in range(5):
    print(i)

OUTPUT:

0
1
2
3
4

The function range(n) creates an iterator that advances the integer numbers from 0 to n. (n -1). We must cast range() with list() to create the list containing these integers, as shown in the example that follows.

list(range(10))

OUTPUT:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range() can also be called with two arguments:

range(begin, end)

The call mentioned above generates a list iterator of integers beginning with begin (inclusive) and ending with a number that is one less than end.

range(4, 10)
list(range(4, 10))

OUTPUT:

[4, 5, 6, 7, 8, 9]

Range() has incremented by 1 thus far. With a third input, we are able to define a different increment. The step is the name for the increase. It can be either positive or negative, but it can't be zero:

range(begin,end, step)

Instance with step:
list(range(4, 50, 5))

OUTPUT:

[4, 9, 14, 19, 24, 29, 34, 39, 44, 49]

You may also do it the other way around:

list(range(42, -12, -7))

OUTPUT:

[42, 35, 28, 21, 14, 7, 0, -7]

As we can see in the example below, the for loop and the range() method work very well together. The for loop uses the values from 1 to 100 supplied by the range() function to calculate the total of these integers:

n = 100

sum = 0
for counter in range(1, n+1):
    sum = sum + counter

print(f"Sum of numbers 1 through 100: {sum}")

OUTPUT:

Sum of numbers 1 through 100: 5050

write your code here: Coding Playground