Repetitive Structures

Python owns a variety of iterative structures such as a string, lists, and functions that permit to iterate through a range of values. To iterate means to repeat an action over some conditions or a statement that is true. In this chapter, we will discuss different forms to iterate through these structures. Particularly, there are several mechanisms to perform a repetitive process, often these mechanisms are called loops. 

Elements of a loop

All loops, contain the following four components:

  1. Initialization of the control variable, will keep track of the times/state of the mechanism of keeping the loop running
  2. A Boolean condition, a.k.a., test/check. This condition will “check” if the Boolean statements remains true, if that is true, then the loop will continue, otherwise (i.e., false), the loop will stop. Remember that we can use relational operators to extract a Boolean expression. 
  3. The body of the loop, This is the set of commands that are redundant in a code, and we wish to repeat in the loop. 
  4. The update of the control variable, The update can be by incrementing/decrementing the control variable in order to accomplish the Boolean condition of the check. The control variable works as an accumulator that will keep track of the current value before reaching a Boolean condition.

All these four components must be satisfy in order to avoid and infinite loop.

The for and the in statement

A way to perform the loop mechanism is by using the for and the in statements to allow the iteration through a set of items. The structure of this loop is as follows:


for control_variable ** in ** collection:
     statement 1
     statement 2
     ...

The control_variable will be used as a place holder that will iterate through each element in the collection provided.

For example, given a string s = “hello” print each character of the string using the for-in statements.

s = "hello"
for character in s :
    print(character)

the program shall print the following

h
e
l
l
o

Processing values using the range function

Python offers a built-in function called range. The function provides a collection (we will discuss several collections through this course, the specific collection that will be provided is a list, and we will discuss more in-depth in Ch. 6) of numbers specified by the number of arguments provided to the function. There are three different versions of range function:

1. range( end) :  the function will provide a collection of numbers starting from 0 and continue one-by-one to number end (not inclusive the end). For example, if we call the function range as follows

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

it will print the values:

2. range ( start, end ): the function will provide a collection of numbers starting from the value start and continue one-by-one to number end (not inclusive the end). For example, if we call the function range as follows

0
1
2
3
4

it will print the values

5
6
7
8

3. range ( start, end, update ): the function will provide a collection of numbers starting from the value start and continue to number end (not inclusive the end) in steps of update. For example, if we call the function range as follows 

for n in range( 0, 25, 5 ):
   print(n)

it will print the values

0
5
10
15
20

The while loop

is similar to the for-loop, but is widely use in constant checking for a condition.

while( <boolean expression> ) :
     statement 1
     statement 2
     ...

Accumulators

In certain problems, requires to keep a variable to accumulate information or aggregate data as a loop is executed or simply to aggregate data in certain stages of a script. These variables are called accumulators. For example, consider the variable named value. Each line of the following sequence accumulates the old value of sum and adds an integer to the new value of sum:

# Accumulators

sum = 0        # initializes sum to be 0
sum = sum + 1  # the new value of sum is composed
print( sum )   # will print 1
sum = sum + 1
print( sum )   # will print 2
sum = sum + 2
print( sum )   # will print 4

Infinite Loops

Infinite loops in python can be provoked intentionally by the computer programmer, or by mistake, whenever one of the four loop components is not satisfied. 

For example, in the following code, the loop will run “forever”

While( True ):
  print("hello forever! ") 

The boolean statement True, will “always” be true, triggering the entire loop to run forever. We can control the loop by:

  • Sentinels
  • Flags
  • Counter/accumulators

Check Point


Tasks

Task 1: Write a script that asks the user to enter a number. Your script shall accumulate the addition of all the values between 0 and that number. E.g., if the user gives you 5, your script shall print 15, since 0 + 1 + 2 + 3 + 4 + 5 = 15

Task 2: Write a script that requests the computer-user to enter a number. This number will represent the number of grades to process. Your program, shall calculate the average AND shall provide the corresponding letter grade. E.g., if the user enters the number 3, your program shall prompt the following:

     Enter Grade: [100]
     Enter Grade: [90]
     Enter Grade: [95]

After the computer-user provides the total number of scores, your script shall display the following message:

     "The toal avg was: 95, and you got: 'A' "

Task 3 :