Control Statements - For Loops


A control statement is a statement that allows the computer to select or repeat an action. Statements generally get run sequentially.

Let's start by looking at loops, which are control statements and is fundamental to programming as whole and not just python.

The thing computers know to do best is do something repeatedly and fast. And certainly loops are what facilitate this ability.

Loops are also known as repetition statements, they repeat an action.

Every repeat is known as a pass or an iteration.

Loops can be divided into two:

  1. Definite Iteration - Loops that perform an action a pre-defined number of times e.g for loops
  2. Indefinite Iteration - Loops that perform an action until the a certain condition is evaluated to false e.g while loops

For Loops

For loops are the most commonly used type of loops. They perform an action a given number of times.

For loops have the following syntax:

for value in iterable:
    pass

Here's a for loop example:

for greeting in range(5):
    print('Am sending you greeting ',greeting)

Let's put it in a class for a more complete snippet like we always do:

class Greetings:
    def send(self):
        for greeting in range(5):
            print('Am sending you greeting ',greeting)

greetings=Greetings()
greetings.send()

Result

Am sending you greeting  0
Am sending you greeting  1
Am sending you greeting  2
Am sending you greeting  3
Am sending you greeting  4

Clearly the print() function is executed 5 times since we have put in a loop.

In our loop you can see that we have the loop header, which is that first line in the loop. The number 5 denotes the number of repeats we want to be performed.

We end the loop header with a colon(:).

After the loop header we have the loop body. It can consists of several statements.However, in this case we have only one, the print() statement.

You always have to indent the statements in the loop body in the same column since python as a language is indentation-sensitive.

The statements get executed in the order they are defined.


Note that in the above example our range() function will start counting at 0 by default.

We can change this by specifying the start ourselves:

class Hello:
    def send(self):
        for num in range(5,10):
            print('Am sending you hello ',num)

hello=Hello()
hello.send()

Result

Am sending you hello  5
Am sending you hello  6
Am sending you hello  7
Am sending you hello  8
Am sending you hello  9

Let's look at example 2.

We want to create a function that can potentially replace the exponentiation operator in python. The exponentiation operator is an operator that raises a number to a given power.

For example 3 ** 3 = 3*3*3 = 27. That is 3 raised to power 3 is 9.

class Exponentier:
    def get_power(self,number,exponent):
        product = 1
        for num in range(exponent):
            product = product * number
        print(number,'raised to power',exponent,'is',product)

exponentier = Exponentier()
exponentier.get_power(3,3)
3 raised to power 3 is 27
  1. We've created a class called Exponentier.
  2. Inside it we have one instance method called get_power().
  3. We pass three parameters in this method. The first one self is mandatory and refers to the instance of this class which will execute this method. The other two(number and exponent) are positional arguments and will be passed when this method is invoked.
  4. We initialize the product to 1.
  5. We pass the exponent inside our range() function. It will define the total amount of repeats we will have.
  6. We multiply the product by number for each iteration and hold the result in the product variable.
  7. Outside the loop we print the product value which is our result.
  8. Outside the class we instantiate the Exponentier class.
  9. Then we invoke the get_power() method passing in the parameters
  10. Change the parameters to see the result.

Loops For Sequence Traversal

The most common uses of loops is not even what simple count-controlled repetitions we've looked above. It is to traverse sequences of data.

The sequences may include lists,dicts,tuples,str etc.

Here's the syntax:

for <variable> in <sequence>:
    # do something

On each pass through the loop the variable is assigned value in the sequence.

List Traversal

Let's look at List Traversal

class Spacecraft:
    def showSpacecrafts(self):
        for spacecraft in ['Casini','Kepler','Spitzer','Voyager A','WMAP']:
            print(spacecraft)

s=Spacecraft()
s.showSpacecrafts()

Result

Casini
Kepler
Spitzer
Voyager A
WMAP

String Traversal

We can also use for loops to traverse strings. Strings are sequences of Unicode characters.

class Camposha:
    def spell_site(self):
        for letter in 'Camposha':
            print(letter)

c=Camposha()
c.spell_site()

Result

C
a
m
p
o
s
h
a

Best Regards.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post