Python Fundamentals – Flow of Control

Python Fundamentals – Flow of Control

CONTROL STATEMENTS

Control statements define the direction or flow in which execution of a program should take place. Control statements also implement decisions and repetitions in programs.
Control statements are of the following two types:

  1.  Conditional branching
  2.  Looping

Conditional brandling, a program is to decide whether or not to execute the next statement(s) based on the resultant value of the current expression. For example, go to IInd year, if you pass Ist year exams, else repeat Ist year (See Figure 12.1).
Looping, the program performs a set of steps or operations repeatedly till a given condition is obtained. Looping for example, add 1 to number x till current value of x becomes 100 is also called iteration. Iteration is a process of executing a statement or a set of statements repeatedly, until some specific condition is specified (See Figure 12.2). All the control structures are further explained in the following sections:

CONDITIONAL STATEMENTS

Many a times in real-life applications, you will need to change the sequence of action based on the specified conditions.
python-fundamentals-flow-of-control-1
python-fundamentals-flow-of-control-2
Sometimes you need to use a simple condition like:

In this statement, the resultant action is taken if the condition is evaluated true (in our case, the weather is cold).
The conditions could be multiple, as in the following conversation:

Python programs can easily handle such chained or nested conditions as long as you write the adequate code. In Python, there are many control structures that are used to handle conditions and the resultant decisions. In this Chapter, you will be introduced to more powerful tools namely, the if. .else, while, and for constructs.

if Statement
The statement if tests a particular condition. Whenever that condition evaluates to true, an action or a set of actions are executed. Otherwise, the actions are ignored. The syn¬tactic form ofstatement is the following:

The expression must be enclosed within parentheses. If it evaluates to a non-zero value, the condition is considered as true and the statement is executed.

Example 1
In the following program, shown as Figure 12.3 a credit card limit is tested for a certain purchase. The value of the variable amount is received from the keyboard, then tested using the if statement. When the condition is true (i.e., the “amount” is less than or equal to 1000), the message “Your charge is accepted” is displayed. If the condition is false, the program ends with a message “The amount exceeds your credit limit”.

if…else Statements
The statement if also allows to answer for the kind of either-or condition by using an else clause. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a false value. The else statement is an optional statement, if provided, in any situation, one of the two blocks get executed not both.
The syntactic form of if-else statement is as follows:

When the expression evaluates to a non-zero value, the condition is considered to be true and statements BLOCK 1 is executed; otherwise, statements BLOCK 2 is executed. Blocks can have multiple lines. As long as they are all indented with the same amount of spaces, they constitute one block. Figure 12.4 shows the flow diagram of if-else statement.
python-fundamentals-flow-of-control-3
A common use of if-else statement is to test the validity of data as given in Example 2.

Example 2
Suppose, you want to write a program that accepts a value of a variable from the user and prints the whether the number is positive or negative. Now write a program using the if-else statement.
The program is shown in Figure 12.5.

Figure 12.5 Demo of if-else statement

Example 3
In the program shown in Figure 12.6, the if statement rearranges any two values stored in x and y so that the smaller number will always be in x and the larger number always in y. If the two numbers are already in the proper order, the compound statement will not be executed.
You will always get the larger value first and then the smaller value.

Figure 12.6 Program using if statement for arranging two numbers

Program to print number is even or odd.

Figure 12.7 Program to print no. is even or odd

Example 5
Program to display menu to calculate sum or product of entered numbers.

Figure 12.8 Program to display menu to calculate sum or product of entered numbers

 Using //Statement with Compound Tasks
In the if statement studied so far, the statement following the condition or the keyword else is a single executable statement, such as an assignment statement. If multiple tasks are to be performed dependent on a condition, then they can be grouped ^together within block to form a single compound statement. Thus, you can use more than one statement as a result of one condition by embedding the statements in a block. In any compound statement, there is no limit on how many statements can appear inside the body, but there has to be at least one. Indentation level is used to tell Python which statement (s) belongs to which block.
If you want to check for several conditions, you can use elif, which is short for “else if”. It is a combination of an if clause and an else clause. Like the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if. The syntax of the if…elif statement is as follows:

Example 6

Figure 12.9 Demo of if…elif…else statement

Nested if Statements
There may be a situation when you want to check for another condition after a condition resolves to true. In such a situation, you can use the nested if construct. In a nested if construct, you can have an if…elif…else construct inside another if…elif…else construct.

Example 7
Suppose that you want to test the ASCII code of a received character to check if it is an alphabetic character. If it is so, you would like to further check if it is in lower case or
upper case. Knowing that the ASCII codes for the upper case letters are in the range 65-90, and those for lower case letters are in the range 97-122. Program shown in Figure 12.9 establishes this logic.
python-fundamentals-flow-of-control-8

LOOPS

Many jobs that are required to be done with the help of a computer are repetitive in nature. For example, calculation of salary of different workers in a factory is given by the(No. of hours worked) x (wage rate). This calculation will be performed by an accountant for each worker every month. Such types of repetitive calculations can easily be done using a program that has a loop built into the solution of the problem. Figure 12.11 shows the flow diagram of loop statement.
python-fundamentals-flow-of-control-4

What is a Loop?
A loop is defined as a block of processing steps repeated a certain number of times. Figure 12.12 illustrates a flowchart showing the concept of looping. It shows a flowchart for printing values 1,2, 3…, 20.
In Step 5 of Figure 12.12, the current value of A is compared with 21. If the current value of A is less than 21, steps 3 and 4 are repeated. As soon as the current value of A is not less than 21, the path corresponding to “NO” is followed and the repetition process stops.
python-fundamentals-flow-of-control-5

The while Statement
The while loop is used to repeat a set of statements as long as a condition is true. In Python, an indefinite loop is implemented using a while statement. An indefinite loop keeps iterating until certain conditions are met. The syntax of while statement is as follows:

Here condition is a Boolean expression. The body of the loop executes repeatedly as long as the condition remains true. When the condition is false, the loop terminates. Notice that the condition is always tested at the top of the loop, before the loop body is executed. This kind of structure is called a pretest loop. If the loop condition is initially false, the loop body will not execute at all. Here is an example of a simple while loop that counts from 0 to 10:

Above program will produce the following output:
1
2
3
4
5
6
7
8
9
10
Figure 12.13 shows the flow of control for a while statement. So long as x is less than y, the program continues to execute the while loop. With each pass through the loop, however, x is incremented by one. When it is no longer less than y, control flows to the next statement.
python-fundamentals-flow-of-control-6

Example 8
Program in Figure 12.14 displays the string “Hello World” five times using the while loop.

Figure 12.14 Program to show ‘Hello World’ five times

Example 9
The program segment shown as Figure 12.15 computes and displays gross pay for seven employees. The loop body (the steps that are repeated) is the compound statement that starts on the seventh line, i.e., after the statement while (count_emp < 7):. The loop body gets an employee’s payroll data and computes and displays pay. After seventh pay amounts are displayed, the last statement “All employees processed” message will be displayed.

Figure 12.15 Computing and display gross pay for 7 employees

In Figure 12.16, the while loop is used to calculate the factorial of a number in this pro-gram, the number is received from the keyboard using the input function and is assigned to the variable “number”.

Figure 12.16 Program to calculate factorial of a number using while loop

Example 11
Write a program to print numbers 1 to 10 using while loop.

Figure 12.17 Print numbers 1 to 10 using while loop

Example 12

Figure 12.18 Print numbers 1 to 10 using while loop

Example 13

Write a program to print even numbers series using while loop.

Example 14
Write a program to print odd numbers series using while loop.

Figure 12.20 Print odd number series using while loop

Example 15
Write a program to print the following pattern:
1
12
123
1234
12345

Example 16
Write a program to print * in the following pattern:
*
**
***
****
*****

Figure 12.22 Nested loop to print * in the given pattern

for Statement
Python provides for statement as another form for accomplishing control using loops. The for loop statement is used to repeat a statement or a block of statements a specified number of times. *•
A Python for loop has this general form.

The body of the loop can be any sequence of Python statements. The start and end of the body is indicated by its indentation under the loop heading. The variable after the key¬word for is called the loop index. It takes on each successive value in the sequence, and the statements in the body are executed once for each value.
Usually, the sequence portion is a list of values. You can build a simple list by placing a sequence of expressions in square brackets. Some interactive examples help to illustrate the point:

the * quick * brown * fox *

The for loop specification ends with a colon, and after the colon (:) comes a block of statements which does something useful with the current element. Each statement in the block must be indented.

Operation of the for Loop
First the initialization expression is executed, then the test condition is examined. If the test expression is false to begin with, the statements in the body of the loop will not be executed at all. If the condition is true, the statements in the body of the loop are executed and, following that, the increment expression is executed. That is why the first number printed by the program is 0 and not 1. Printing takes place before the number is incremented by increment (++) operator. Finally the loop recycles and the test expres¬sion is queried again. This will continue until the test expression becomes false-number becomes 10 in this case —at which time the loop will end.

The rangeO Function
If you do need to iterate over a sequence of numbers, the built-in function range() is used. It generates lists containing arithmetic progressions:

The given end point is never part of the generated list; range(lO) generates a list of 10 values, the legal indices for items of a sequence of length 10.
It is possible to let the range start at another number, or to specify a different increment (even negative) called the step:

The for Loop and the range() Built-in Function
The for statement acts more like a traditional loop, in other words, a numerical counting loop.

Within our loop, eachNum contains the integer value that we are displaying and can use it in any numerical calculation we wish. Because our range of numbers may differ, Python provides the range() built-in function to generate such a list for us. It does exactly what we want, taking a range of numbers and generating a list.

Note that range(n) generates integers 0,1, 2,…, n-1. For example,

range(start/ stop, step) generates a sequence if integers start,start+step, start+2*step, and so on up to, but not including, stop. For example, range(2, 8, 3) returns 2 and 5 (and not 8), while range(l, 11, 2) returns 1,3, 5, 7, 9.
range(start, stop) is the same as range(start, stop, 1).
A for loop over integers are written as:

The following program writes the numbers from 1 to 100:

An integer to add to the current number to generate the next number. (This is called a step.) If left out, it defaults to 1. So above program will be written as:

Example 17
Program to print values 1 to 10 using for loop.

Figure 12.23 Program to print numbers 1 to 10

 

Example 18
Program to print even number series up to 20
python-fundamentals-flow-of-control-9

Example 19
Program to print sum of even number series up to 10.

Figure 12.25 Program to print sum of even numbers

Example 20
Program to generate of multiplication table.

Figure 12.26 Program to print table of desired number

Example 21

Program to print letters of word

Figure 12.27 Program to print letters of entered word

Example 22
Program to print ASCII code for entered message.
NESTED LOOPS
A loop may also contain another loop within its body. This form of a loop inside a loop is called nested loop. In a nested loop construction, the inner loop must terminate before the outer loop can be ended.

Example 23
Write a program to print following pyramid using for loop:
* *
* * *
* * * *
* * * * *

Figure 12.29 Nested loop

The print statement by default automatically add a Newline character at the end of every line. This can be suppressed by terminating the print statement with a comma (,).

JUMP STATEMENTS
Those statements which transfer the program control, unconditionally with in the pro¬gram, from one place to another are called jump statements. These statements include the following statements: ,
(a) break Statement
(b) continue Statement
(c) pass Statement

break Statement
The break statement causes an immediate exit from the innermost loop structure. The break statement transfers control out of a while or for, statement. Break is mostly required, when due to some external condition, we need to exit from a loop.
If you need to come out of a running program immediately without letting it to perform any further operation in a loop, then you can use break statement. The break statement exits out of the current loop (for or while) and transfers control to the statement immediately following the control structure.
Figure 12.30 shows the use of break statement.

Example 24

Figure 12.30 Demo of using break statement

Note that in the following example break statement causes Python to immediately exit the loop so it will print COMP.
Example 25

Figure 12.31 Demo of using break statement

 

continue Statement
The continue statement forces the next iteration of the loop to take place, skipping any statement(s) following the continue statement in the body of the loop, i.e., continue statement jumps back to the top of the loop.
The syntax of the continue statement is :

continue
The statement continue can be considered as the opposite of break statement, continue statements used to skip the rest of the body of the loop and the next iteration after the loop begin immediately.
Figure 12.32 shows the use of continue statement. At the top of the loop, the while con-dition is tested and loop is entered again, if it’s true. So, when count is equal to 5, the program does not get to the print count statement. The number 5 is skipped with a continue statement and loop ends through a break statement.

Example 26

Figure 12.32 Demonstration of using continue statement

Example 27

Figure 12.33 Demonstration of using continue statement Note that U is skipped in the above program due to use of continue statement.

Difference between break and continue statement
The continue statement skips the remainder of the statements in the body of a loop and starts immediately at the top of the loop again.
A break statement in the body of a loop terminates the loop. It exits from the immedi¬ately containing loop.
break and continue can be used in both for and while statements.

pass Statement
The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet. For example,

It can be useful as a placeholder while you are writing code. For example, you may have written an if statement and you want to try it, but you lack the code for one of your blocks. Consider the following:

This code won’t run because an empty block is illegal in Python. To fix this, simply add a pass statement to the middle block:

Solved Exercise

Question 1. 
What is conditional branching?
Answer:
Conditional branching, a program is to decide whether or not to execute the next statement(s) based on the resultant value of the current expression. For example, go to IInd year, if you pass Ist year exams, else repeat Ist year.

Question 2. 
What is looping?
Answer:
Looping, the program performs a set of steps or operations repeatedly till a given condition is obtained. Looping for example, add 1 to number x till current value of x becomes 100 is also called iteration. Iteration is a process of executing a statement or a set of statements repeatedly, until some specific condition is specified.

Question 3. 
Explain if statement.
Answer:
The statement if tests a particular condition. Whenever that condition evaluates to true, an action or a set of actions are executed. Otherwise, the actions are ignored.

Question 4. 
Explain range() function with an example.
Answer:
If you do need to iterate over a sequence of numbers, the built-in function range() is used. It generates lists containing arithmetic progressions:

The given end point is never part of the generated list; range(lO) generates a list of 10 values, the legal indices for items of a sequence of length 10.

Question 5. 
What is the similarity and difference between break and continue statements. Similarity: Both break and continue are jump statements.
Answer:
Difference: The break statement terminates the entire loop execution where as con¬tinue statement is used to bypass the remainder of the current pass through a loop. The loop does not terminate when a continue statement is encountered. Rather, the remaining loop statements are skipped and the computation proceeds directly to the next pass through the loop.

Question 6. 
What is the function of break statement in a while or for loop?
Answer:
If a break statement is included in a while, or for loop, then control will immediately be transferred out of the loop when the break statement is encountered. This provides a convenient way to terminate the loop if an error or other irregular condition is detected.

Question 7. 
Write a program to print the first few terms in a Fibonacci series.
Answer:

Figure 1 Program for Q7

Question 8. 
Give the output of the following programs:
(a)

(b)

(c)

The output of the (a), (b) and (c) are as follows:
Answer:

Figure 2 Output for Q8(a)

Answer:

Figure 3 Output for Q8(b)

Answer:

Figure 2 Output for Q8(c)

Question 9. 
Write a program using while loop that asks the user for a number, and prints a countdown from that number to zero. Note: Decide what your program will do, if user enters a negative number.
Answer:

Figure 5 Program for Q9

Question 10. 
Print all multiples of 13 that are smaller than 100. Use the range function in the fol-lowing manner: range (start, end, step) where “start” is the starting value of the counter, “end” is the end value and “step” is the amount by which the counter is increased each time.
Answer:

Figure 6 Program for Q10

Question 11. 
Write a program to enter a digit from the keyboard and then print the sum of the values of the digits of the number. It also reverses the number.
Answer:

Figure 7 Program for Qll

Question 12. 
What do you mean by flow-of-control statements.
Answer:
Statements that are executed one after the other or the statements that are executed sequentially is the normal flow-of-control statements in a program
python-fundamentals-flow-of-control-7

Question 13. 
What do you mean by selection statements?
Answer:
In some programs, you may need to change the sequence of execution of instructions according to specified conditions is called selection statements.

Question 14. 
What is the minimum number of iteration that while loop could make?
Answer:
while loop could make 0 iteration.

Question 15. 
What is the difference between entry controlled loop and exit controlled loop?
Answer:
In an entry controlled loop, the loop control condition is evaluated at the entry point of the loop. However, in an exit controlled loop, the loop control condition is evalu¬ated at the exit point of the loop.
If the loop control condition is false in the beginning, the entry control loop is never executed. However, the exit control loop would be executed at least once.

Question 16. 
What are jump statements?
Answer:
Jump statements are statements that allow you to transfer control to another part of your program.

Question 17. 
What is Iteration?
Answer:
It is a process of executing a statement or a set of statements repeatedly, until some specific condition is specified.

Multiple Choice questions

Question 1. 
The operator & is used for:
(a) Bitwise AND
(b) Bitwise OR
(c) Logical AND
(d) Logical OR
Answer: (a)

Question 2. 
A “Python” expression contains relational, assignment and arithmetic operators. There are no parentheses used. They will be evaluated in which of the following
order:
(a) Assignment Relational Arithmetic
(b) Arithmetic Relational Assignment
(c) Relational Arithmetic Assignment
(d) Assignment Arithmetic Relational
Answer: (b)

Question 3. 
We can go back to the start of the loop by using:
(a) break
(b) continue
(c) pass
(d) None of these
Answer: (b)

Question 4. 
The && and | | operators:
(a) Compare two numeric values
(b) Combine two numeric values
(c) Compare two boolean values
(d) None of the above
Answer: (c)

Question 5. 
The condition on which the execution or exit of the loop depends is called :
(a) exit condition
(b) test condition
(c) Both (a) and (b)
(d)None of these
Answer: (c)

About the author

James Palmer

Leave a Comment