Generally a program executes its statements from beginning to end. But not many programs execute all their statements in strict order from beginning to end. Programs, depending upon the need, can choose to execute one of the alternatives or even repeat a set of statements. To perform their manipulative miracles, programs need tools for performing repetitive actions and for making decisions. Python, of course, provides such tools by providing statements to attain so. Such statements are called program control statements. This session deals with such statements in detail.
Contents
TYPES OF STATEMENTS IN PYTHON
Statements are the instructions given to the computer to perform any kind of action, be it data movements, and be it making decisions or be it repeating actions. Statements from the smallest executable unit within a python program. Python statements can belong to one of the following three types:
- Empty statement (Null statement): The simplest statement is empty statement i.e., a statement which does nothing. In python empty statement is pass statement. Whenever Python encounters pass statement it does nothing and moves to next statement in flow of control.
A pass statement is useful in those instances where the syntax of the language requires the presence of a statement but where the logic of the program does not. We will see it in loops and their bodies.
- Simple statement (single statement): Any single executable statement is a simple statement in Python. For example, following is a simple statement in Python:
Name= input(“Your name”)
As you can make out that simple statements are single line statements.
- Compound statement: A compound statement represents a group of statements executed as a unit. The compound statements of Python are written in a specific pattern as shown below:
<compound statement header>:
<indented body contains multiple simple/ compound statements>
That is a compound statement has:
- A header line which begins with a keyword and ends with a colon.
- A body consisting of one or more Python statements, each indented inside the header line. All statements in the body are at the same level of indentation.
STATEMENT FLOW CONTROL
In a program, statements may be executed sequentially, selectively or iteratively. Every programming language provides constructs to support sequence, selection or iteration.
Sequence
The sequence construct means the statements are being executed sequentially.
Every Python program begins with the first statement of program. Each statement in turn is executed (sequence construct). When the final statement of program is executed, the program is done. Sequence refers to the normal flow of control in a program and is the simplest one.
Selection
The selection construction means the execution of statements depending upon a condition test. If a condition evaluates to True, a course of action is followed otherwise another course of action is followed. This construct is also called decision construct because it helps in making decision about which set of statements is to executed.
You can apply decision making or selection in your real life so many times e.g., if the traffic signal light is red, then stop; if the traffic signal light is yellow then wait; and if the signal light is green then go.
You can think of many such real life examples.
Repetition Iteration (Looping)
The iteration constructs mean repetition of a set of statements depending upon a condition test. Till the time a condition is True (or False depending upon the loop), a set of statements are repeated again and again. As soon as the condition False (or True), the repetition stops. The iteration construct is also known as looping construct.
The set of statements that are repeated again and again is called the body of the loop. The condition on which the execution or exit of the loop depends is called the exit condition or test condition.
You can find many examples of iteration or looping around you. For instance, you often see your mother cook chapatis or dosas or appams for you.
Let’s see, what she does for it:
- Put rolled chapatti or dosa batter on flat pan or tawa
- Turn it 2-3 times
- Once done it take it off
You can find numerous other examples of repetitive work in your real life e.g., washing clothes; colouring in colouring book etc..
Every programming language must support these three types of constructs as the sequential program execution (the default mode) is inadequate to the problems we must solve. Python also provides statements that support these constructs.
THE if STATEMENTS OF PYTHON
The if statements are the conditional statements in Python and these implement selection constructs.
An if statement tests a particular condition; if the condition evaluates to True, a course of action is followed i.e., a statement or set of statements is executed. Otherwise, the course of action is ignored.
THE if STATEMENT
The simplest form of if statement tests a condition and if the condition evaluates to true, it carries out some instructions and does nothing in case condition evaluates to false.
The if statement is a compound statement and its syntax (general form) is as shown below:
if <conditional expression>:
statement(s)
where a statement may consist of a single statement, a compound statement, or just a pass statement. In an if statement; if the conditional expression evaluates to true, the statements in the body of if are executed, otherwise ignored.
Now let us consider an example that uses two if statements:
ch= input(“Enter a single character:”)
if ch==’ ‘:
print(“You entered a space”)
if ch>=’0’ and ch<=’9’:
print(“You entered a digit”)
The above code example reads a single character ch. If the character input is a space, it flashes a message specifying it. If the character input is a digit, it flashes a message specifying it.
THE if-else STATEMENT
This form of if statement tests a condition and if the condition evaluates to true, it carries out statements indented below if and in case condition evaluates to false, it carries out statements indented below else. The syntax of the if-else statements is as shown below:
if <conditional expression>:
statement(s)
else:
statement(s)
For instance, consider the following code fragment:
a= int(input(“Enter a number:”))
if a>0:
print(a, “is zero or a positive number”)
else:
print(a, “is a negative number)
THE if-elif STATEMENT
Sometimes, you need to check another condition in case the test condition of if evaluates to false. That is, you want to check a condition when control reaches else part, i.e., condition test in the form of else if.
The general form of these statements is:
if < conditional expression>:
statement(s)
elif <conditional statement>:
statement(s)
else:
statement(s)
THE nested if STATEMENT
Sometimes above discussed forms of if are not enough. You may need to test additional conditions. For such situations, Python also supports nested-if form or if.
A nested if is an if that has another if in its if’s body or in elif’s body or in its else’s body.
The nested if can have one of the following forms:
FORM 1:
if < conditional expression>:
if < conditional expression>:
statement(s)
else:
statement(s)
elif <conditional statement>:
statement(s)
else:
statement(s)
FORM 2:
if < conditional expression>:
statement(s)
elif <conditional statement>:
if < conditional expression>:
statement(s)
else:
statement(s)
else:
statement(s)
FORM 3:
if < conditional expression>:
statement(s)
elif <conditional statement>:
statement(s)
else:
if < conditional expression>:
statement(s)
else:
statement(s)
FORM 4:
if < conditional expression>:
if < conditional expression>:
statement(s)
else:
statement(s)
elif <conditional statement>:
if < conditional expression>:
statement(s)
else:
statement(s)
else:
if < conditional expression>:
statement(s)
else:
statement(s)
In a nested if statement, either there can be if statement(s) in its body of if or in its body of elif or in its body of else or in any two of these or in all of these.
ITERATION/LOOPING STATEMENTS
The iteration statements or repetition statements allow a set of instructions to be performed repeatedly until a certain condition is fulfilled. The iteration statements are also called loops or looping statements. Python provides two kinds of loops : for loop and while loop to represent two categories of loops, which are:
- Counting loops: the loops that repeat a certain number of times; Python’s for loop is a counting loop.
- Conditional loops: the loops that repeat until a certain thing happens i.e., they keep repeating as long as some condition is true; Python’s while loop is conditional loop.
THE for LOOP
The for loop of python is designed to process the items of any sequence , such as a list or a string, one by one. The general form of for loop is as given below:
for <variable> in <sequence>:
statement_to_repeat
For example, consider the following loop:
for a in [1,2,3,4]:
print(a)
print(a*a)
A for loop in Python is processed as:
- The loop variable is assigned the first value in the sequence.
- All the statements in the body of for loop are executed with assigned value of loop variable.
- Once step 2 is over, the loop variable is assigned the next value in the sequence and the loop body is executed with the new value of loop variable.
- This continues until all values in the sequence are processed.
THE while LOOP
A while loop is a conditional loop that will repeat the instructions within itself as long as a conditional remains true. The general form of python while loop is:
while <logical_expression>:
loop body
where the loop body may contain a single statement or multiple statements or an empty statement. The loop iterates while the logical expression evaluates to true. When the expression becomes false, the program control passes to the line after the loop body.
To understand the working of while loop, consider the following code:
a=5
while a>0:
print(“hello”,a)
a=a-3
print(“loop over!!”)
The above code will print:
hello 5
hello 2
loop over!!
JUMP STATEMENTS
Python offers two jump statements to be used within loops to jump out of loop iterations. These are break and continue statements.
THE break STATEMENT
The break statement enables a program to skip over a part of the code. A break statement terminates the very loop it lies within. Execution resumes at the statement immediately following the body of the terminated statement.
The following code fragment gives you an example of a break statement:
a=b=c=0
for i in range(1,21):
a=int(input(“Enter number 1:”))
b= int(input(“Enter number 2:”))
if b==0:
print(“Division by zero error! Aborting!”)
break
else:
c=a//b
print(“Quotient=”,c)
print(“Program over”)
The above code fragment intends to divide ten pairs of numbers by inputting two numbers a and b in each iteration. If the number b is zero, the loop is immediately terminated displaying message “Division by zero error! Aborting!” otherwise the numbers are repeatedly input and their quotients are displayed.
THE continue STATEMENT
The continue statement is another jump statement like the break statement as both the statements skip over a part of the code. But the continue statement is somewhat different from break.
Instead of forcing termination, the continue statement forces the next iteration of the loop to take place, skipping any code in between.
NESTED LOOPS
A loop may contain another loop in its body. This form of a loop is called nested loop. But in a nested loop, the inner loop must terminate before the outer loop. The following is an example of a nested loop, where a for loop is nested within another for loop.
Example:
for i in range(1,6):
for j in range(1,i):
print(“*”,end=’ ‘)
print()
Output:
*
* *
* * *
* * * *
The inner for loop is executed for each value of i. The variable i takes values 1,2,3 and 4. The inner loop is executed once for i=1 according to sequence in inner loop range(1,i) (because for i as 1, there is just one element 1 in range (1,1) thus j iterates for one value,i.e., 1), twice for i=2(two elements in sequence range(1,i)), thrice for i=3 and four times for i=4.
While working with nested loops, you need to understand one thing and that is, the value outer loop variable will change only after the inner loop is completely finished.