Lesson 8: Repetitions

Learn python programming in 12 lessons


You should remember from the previous posts that an algorithm has steps, decisions and receptions of steps. By repetitions, we mean loops and Python supports two loop structures
  • for loop
  • while loop
These structures are further enhanced by loop control statements such as break, continue and the pass.
Loops can also be used to alter the flow of the program by executing them when some conditions are met by using if statements. This pretty much means that there is no limits as to what you can do with loops, you can have multiple loops inside each other but this is not recommended especially when you are dealing with large input data.

A loops would have 2 main elements, namely the body which entails the steps to be repeated, the terminating condition which is tested on each iteration of the loop. You can also call the terminating condition as a guard condition because it guards the body from being executed if the control statement does not evaluate to true.

Say we wanted to alter our program AddThreeNums.py so that it finds the average of more than three numbers depending on how many numbers the user wants to enter and print the new average every time a new number is entered. We can use a for loop and the program would look like this


# Program to display the average of three numbers on the screen
# Take note that using eval() function is equivalent to using int()


def getNumber():
    return input("Enter a number: ")

def main():
    itr = int(input("How many numbers would you like to enter: "))
    total = 0
    average = 0
   
    for i in range (itr):
       
        num=getNumber()
        total += eval(num) # equivalent to total = total + eval(num)
        average = total/(1+i) # equivalent to average = average + total/(i+1)
        print("\nTotal:", total)
        print("Average:", average)

if __name__ == '__main__':
    main()

A for loop has the following structure

for var in sequence:
    body
var is the variable that keeps track of the loops iterations
sequence is range of numbers var can hold at each iteration.
body represents all steps that need to be repeated

The line for i in range (itr): can be represented in 5 different ways. Assume that itr = 10, then the following lines would mean

for i in range (itr) means i can take on values 0,1,2,3,4,5,6,7,8,9
for i in range (1,itr) means i can take on values 1,2,3,4,5,6,7,8,9
for i in range (0,itr,2) means i can take on values 0,2,4,6,8
for i in range (itr,1,-1) means i can take on values 10,9,8,7,6,5,4,3,2
for i in range (-itr,0) means i can take on values -10,-9,-8,-7,-6,-5,-4,-3,-2,-1

The other loop structure is the while loop and this loop has the following structure

while condition
    body
condition is the guard statement that permits the steps outlined in the body to be repeated only if the condition evaluates to true. So you can see that the while and for loop are interchangeable. The for loop in the AddThreeNums.py program can also be replaced by the while loop to achieve the same result as shown here


# Program to display the average of three numbers on the screen
# Take note that using eval() function is equivalent to using int()


def getNumber():
    return input("Enter a number: ")

def main():
    itr = int(input("How many numbers would you like to enter: "))
    total = 0
    average = 0
   
    i = 0
    while (i != itr):
       
        num=getNumber()
        total += eval(num) # equivalent to total = total + eval(num)
        average = total/(1+i) # equivalent to average = average + total/(i+1)
        print("\nTotal:", total)
        print("Average:", average)
        i += 1  # equivalent to i = i + 1

if __name__ == '__main__':
       main()

Share your thoughts