Control Structures

Back To The Index 

ControlStructures

Each of the individual instructions in the programm, is a simple Python statement. At the run time, the statements are executed in the order in which they appear in the program. But modern programming is not just about visiting sequential instructions first to last, one at a time in monotonic fashion. Very often, we need a program to repeatedly execute certain segments of code, or make decisions and choose one chunk to execute over the other. It’s these kind of situations where execution control structures are needed to determine the behavior of our program unique to the circumstance of operation.

Selection Statements : if, elif, else

The keyword if causes one or more statements to be executed, if, and only if, a condition is fulfilled. The Python syntax is:

if (condition): statement1 statement2 statement3 the_next_statement

When execution encounters the if keyword, it evaluates condition expression. If it is True, the statement1, statement2, statement3 are executed, but if it is False, the execution ignores statement, and moves on to the_next_statement. Execution considers all nested statements after if(condition): part of its scope, until it hits the one that is not nested (see the_next_statement).

For example, consider a situation where we need to calculate the quotient between numbers Y and X and assign it to an identifier Q.

In [ ]:
Q = X/Y

Above statement works whenever Y$\neq$0, and runs into trouble otherwise. The way out ofcourse is to make sure that it gets executed only when Y$\neq$0 is satisfied. See the self explanatory snippet below and note how Q = X/Y is executed only when Y $\ne$ 0.

In [ ]:
#Set Default Value for Q
Q = 0
if Y != 0.0 :
    Q = X/Y

The selection statements in Python also allow us to specify what happens when the condition is not fulfilled, by using keywords else and elif. For example lets look how to Calculate the absolute value of a number:

In [ ]:
mode_Y = None
if Y < 0:  # If y<0 then absolute value is -y
    mode_Y = -1*Y
elif Y > 0: # If y>0 then absolute value is y
    mode_Y = Y
else:
    mode_Y = 0

Here we perform a 3 way decision, and make sure that a different statement gets executed for each of the included scenarios. If Y is less then 0, identifier mode_Y is assigned value -1$\times$Y,and when Y is greater than 0 its assigned value Y but if none of those conditions are true then mode_Y = 0. Thus keyword elif allows us to cascade multiple scenarios after initial if clause, and finally the else decides what is to be executed when none of the previous conditions evaluate to True.

Iteration Statements (loops) : while, for

Loops cause a statement be repeated a certain number of times, or as long as a condition is fulfilled. Most common way to introduce loops in Python is with keyword for and somewhat less oftenly with keyword while.

The for Loop

The for loop is designed to iterate a number of times. Its syntax is:

for i in range(start, end, stepsize): statement1 statement2 the_next_statement

At the first iteration identifier i is assigned value= start. It is then incremented by stepsize at each successive iteration. The loop keeps iterating while i $\lt$ end, executes all statements in within its scope at each pass, and then execution goes to the_next_line. Like in if statements, the scope of for statement is the set of all nested statements after (:) untill the first unnested one i.e (the_next_statement) is reached.

In [ ]:
for i in range(1,11):
    print (i)
print (I am out of the loop)

Here the statement for i in range(1,11): forces the print statement to repeat 10 times. The number of iterations 10, is determined by the arguments (1,11) to the range call. At the first execution the variable i has value =1, which then gets incremented to next number at each successive iteration. Each pass calls print with current value of i as argument, and we see numbers printed out on screen.

1 2 3 4 5 6 7 8 9 10 I am out of the loop

The while Loop

The while loop is designed to iterate while a condition holds true. Its syntax is:

while (expression): statement1 statement2 the_next_statement

The while-loop simply repeats statement while expression is true. If, after any execution of statements in its scope, the expression stops holding True, the loop terminates, and the execution passes right on to statement next to loop (the_next_statement). Let us consider the task of calculating factorial of a given number :

In [3]:
factorial = 1
number = 100
while (number > 1):
    factorial = factorial * number
    number = number -1 
print ("The factorial of ",100," is ",factorial)

The first statement initialize factorial to 1, and number to 100. Then the while-loop begins: if the current value of number value fulfills the condition number>1, then the following block of statements in scope is executed, and repeated for as long as the condition remains true.

The Rude Jump Statements : continue, break

The break statement, like in C, breaks out of the innermost enclosing for or while loop. The continue statement whenever executed casues rest of the scope to be byepassed, and loops begins the next iteration

Conclusions

We learned following concepts in this tutorial:

  1. Idea of control structures
  2. Control through Conditional Statements (if,elif,else)
  3. Control through Loop Statements ( for, while )
    • The Jump Statements
 Back To The Index