2. Flow Control

Authors : Dr.Thyagaraju G S and Palguni G T

A programs control flow is the order in which the program’s code executes. The control flow of a python program is regulated by conditional statements, loops, and function calls. Real strength of program is not just running or executing instructions sequentially one after the other, but skipping and iterating instructions based on the conditions. Flow control statements can decide which Python instructions to execute under which conditions.

2.1 Boolean Values: 

A Boolean value is either true or false. It is named after the British mathematician, George Boole, who first formulated Boolean algebra. In Python the two Boolean Values are True and False and the Python type is bool. Enter the following into the Python shell and observe the output.

Code Snippet 1:

Code Snippet 2:

2.2 Boolean Expression

A Boolean expression is an expression that evaluated to produce a result which is a Boolean value. For example, the operator == tests if two values are equal. It produces (or yields) a Boolean value:

In the first statement the two operands evaluate to equal values, so the expression evaluates to True; in the second statement, 5 is not equal to 6 we get False.

2.3 Comparison Operators

Comparison operators compare two values and evaluate down to a single Boolean value. The == operator is one of six common comparison operators which all produce a bool result. Table lists all the comparison operators:

OperatorMeaning
==Equal to
!=Not Equal to
Less than
Greater than
<=Les than or equal to
>=Greater than or equal to

Comparison operators evaluate to True or False depending on the values we provide to them .

Based on the above observations it is clear that == (equal) evaluates to True when the value on both sides are the same , and != (not equal to ) evaluates to True when the two values  are different . T Equal to and Not equal to operators can work with values of any data type.

The other comparison operators like <, >, <= and >= work properly only with integer and floating-point values.

Difference between == and = Operator

===
It is an assignment operatorIt is a comparison operator
It is used for assigning the value to a variableIt is used for comparing two values.  It returns 1 if both the value is equal otherwise returns 0
Constant term cannot be place on left hand side Example: 1= x; is invalidConstant term can be placed in the left-hand side. Example: 1 ==1 is valid and return 1

2.4 Boolean Operators:

Boolean operators evaluate the expression to Boolean Values True/False. Python supports three Boolean operators and, or & not. Based on the number of operands required they can be classified into Binary Boolean operators and Unary Boolean Operators.

Binary Boolean operators : and & or

Since both and & or operators takes two operands, they are considered as binary operators. The and operator returns true value if both operands are true and return false otherwise. While or operator returns false when both operands are false and returns true otherwise.

Following truth tables illustrates all possible logical combinations and values for OR and AND Boolean binary operators

Truth Table for AND

Op1Op2Op1 and Op2
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse
TrueTrueTrue

Truth Table for OR

Op1Op2Op1 or Op2
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse
TrueTrueTrue

Not operator:

It is a unary operator and evaluates the expression to  opposite value true or false as illustrated below :

Truth Table for not operator:

opnot op
TrueFalse
FalseTrue

Examples for Mixing Boolean and Comparison Operators:  Boolean operators and comparison operators can be used in combination as illustrated below :

2.5 Elements of Flow Control:

Program Execution: 

Program is a set of statements. The statements in Python are executed sequentially one after the other from the beginning of the program to the end of a program. This kind of program execution where in the control flows sequentially is termed as sequential execution of program.  In some context it becomes inevitable to skip certain set of statements in order to execute another set of statements. This type of program execution is termed as selective execution. In Python language the selective execution is achieved using the statements known as Branching statements or Conditional control structures or statements.Also, in certain situations a set of statements has to be executed repeatedly for given number of times. This is achieved with the help of Loop Control constructs or statements. The mechanism of repeating one or more statements execution either for a fixed number of times or until certain condition is satisfied is termed as Looping.

Flow control statements often starts with condition followed by a block of code called clause.

Conditions:

Conditions are Boolean expressions with the boolean values True or False. Flow control statements decides what to do based on the condition whether it is true or false.

Blocks of Code /Clause:

The set of more than one statements grouped with same indentation so that they are syntactically equivalent to a single statement is known as Block or Compound Statement. One can tell when a block begins and ends based on indentation of the statements . Following are three rules for blocks :

  1. Blocks begin when the indentation increases
  2. Blocks can have nested blocks
  3. Blocks end when the indentation decreases to zero

Example1 :

Example 2: Nested Blocks

The control and flow of a program in any programming language can be broadly classified into three categories:

  1. Sequential
  2. Selection or Branching
  3. Iteration or looping

In Python program, statements can be executed sequentially , selectively or iteratively . The following section discuses the program control flow constructs in brief .

  1. Sequential:

Here the program are executed in a sequential order or in a linear fashion , one after another without skipping or any jump in the program.As illustrated in the figure below  Statement1 will be executed first followed by statement 2  , statement3 ,——statementn.

2. Selection or Branching Statements:

These are the statements which will transfer control flow from one place to another place, so as to execute a set of instructions ,if some condition is met or, to skip the execution of the statements if the condition is not met. They are also known as Conditional selection statements or decision statements. They specify the order in which computation are performed. The Python programming statement which provides two paths to control flow to follow one for the true condition and the other for the false condition as shown in figure is called two-way selection statement.

Types of Condition Control Statements

The different two-way selection statements supported by Python language are:

  1. if statement
  2. if- else statement
  3. Nested if else statement
  4. if – elif  ladder
  1. if statement

It is basically a two way decision statement and it is used in conjunction with an expression. It is used to execute a set of statements if the condition is true. If the condition is false it skips executing those set of statements. The syntax and flow chart of if statement is as illustrated below:

Example1: Python program to find the largest number using if statement.

Example2: Python Program to determine whether a person is eligible to vote using if.

2. If else statement:

It is an extension of if statement. It is used to execute any one set of two set of statements at a time. If condition is true it executes one set of statements otherwise it executes another set of statements. The syntax and flow diagram of if else is as shown in the figure below. As illustrated in the figure if the condition is true the set of statements {S11,S12,——S1n} gets executed else if the condition is false the set of statements {S21,S22,S23——S2n} gets executed.

Example: Program to check whether a given number is even or odd using if else.

3. Nested if else: 

When a series of decisions are involved, we may have to use more than one if else statement in nested form. The nested if else statements are multi decision statements which consist of if else control statement within another if or else section. The syntax and flow diagram for nested if else is as shown below:

Example:

4. if – elif ladder:

Cascaded if elif else is a multipath decision statements which consist of chain of if elseif  where in the nesting take place only in else block. As soon as one of the conditions controlling the ‘if’ is true , then statement /statements associated with that ‘if’ are executed and the rest of the ladder is bypassed. If condition is false then it checks the first elif condition , if it is found true then first elif is executed. However, if none of the elif ladder is correct then the final else statement will be executed and control flows from top to down.

The syntax and flow diagram for cascaded if else is as shown in figure.

Example:

3. Iteration or looping:

The statement which are used to repeat a set of statements repeatedly for a given number of times or until a given condition is satisfied is called as looping constructs or looping statements. The set or block of statements used for looping is called loop.

Types of Looping statements:

Depending on the position of the control statement in the loop the looping statements are classified into the following two types:

  1. Entry controlled Loop
  2. Exit Controlled Loop

1. Entry Controlled Loop: In the entry controlled loop the control conditions are tested before the start of the loop execution. If the conditions are not satisfied, then the body of the loop will not be executed. It is also known as pretest loop or top test loop. The flow chart for the entry controlled loop is as illustrated in fig .

2.Exit Controlled Loop: In the exit controlled loop the test is performed at the end of the body of the loop and therefore the body is executed unconditionally for the first time. It is also known as posttest loop. Here the body of the loop will get executed at least once before testing.The flow chart for the exit controlled loop is as illustrated in fig .

The looping includes the following four steps:

1. Initialization of a condition variable

2. Testing for a specified value of the condition variable for execution of the loop.

3. Execution of the statements in the loop

4. Updating (Incrementing or Decrementing) the condition variable

Types of Loops Supported in Python:

The Python Language supports the following two looping operations:

  1. The while statement
  2. The for statement

The while statement: It is an entry controlled loop statement. In case of while loop the initialization, testing the condition and incrementation or updation is done in separate statements. First initialization of the loop counter is performed.Next the condition is checked. If the condition evaluates to be true then the control enters the body of the loop and executes the statements in the body.

  1. The syntax or basic format of the while statement is   as shown  in figure 2.9  below :

While statement in Python executes a block of code repeatedly as long as the test/control condition of the loop is true. The control condition of the while loop is executed before any statement in the body of the loop is executed . If the condition is true, the body of the loop is executed. Again, the control condition of the loop is tested, and the loo continue as long as the condition remains true. When the test outcome of this condition remains true. When the test outcome of this condition becomes false, the loop is not entered again and the control is transferred to the statement immediately following the body of the loop as shown in the flow diagram.

Example: Program to find the sum of n natural numbers using while loop.

For loop:

The for loop is another entry-controlled loop. It is used to execute the set of statements repeatedly over a range of values or a sequence. With every iteration of the loop, the control variable checks whether each of the values in the range has been traversed or not. When all the items in the range are traversed the control is then transferred to the statement immediately following for loop.

Syntax of for loop :

for<control_variable> in <sequence/items in range>:

<statements in body of the loop>

else:              # optional

<Statements>

Flow Chart:

Example: Python Program to find the sum of natural numbers upto n.

range ( ) function:

The range() function returns a sequence of numbers , starting from 0 to a specified number, incrementing each time by 1.

Syntax :

                    range(start,step,stop)

Example :

CommandOutput
range(10)[ 0,1,2,3,4,5,6,7,8,9]
range(1,11)[ 1,2,3,4,5,6,7,8,9,10]
range(0,30,5)[0,5,10,15,20,25]
range(0,-9,-1)[0,-1,-2,-3,-4,-5,-6,-7,-8

The argument of range() function must be integers. The step parameter can be any positive or negative integer other than zero.

Infinite Loop:

A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.

An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required.

Nested Loops:

Python programming language allows to use one loop inside another loop.

Syntax for nested for loop:

for iterating_var in sequence:

   for iterating_var in sequence:

      statements(s)

   statements(s)

Example:

Syntax for nested while loop:

The syntax for a nested while loop statement in Python programming language is as follows –

while expression:
   while expression:
      statement(s)
   statement(s)

A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example a for loop can be inside a while loop or vice versa. The following program uses a nested for loop to find the prime numbers from 2 to 20−

Jump statements:

You might face a situation in which you need to exit a loop completely when an external condition is triggered or there may also be a situation when you want to skip a part of the loop and start next execution.

Python provides break and continue statements to handle such situations and to have good control on your loop.

break :

The break statement in Python terminates the current loop and resumes execution at the next statement, just like the traditional break found in C.

The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.

continue

The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.

The continue statement can be used in both while and for loops.

Example:

else statement used with loops :

Python supports to have an else statement associated with a loop statements.

  • If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.
  • If the else statement is used with a while loop, the else statement is executed when the condition becomes false.

Example :

The following example illustrates the combination of an else statement with a for statement that searches for prime numbers from 10 through 20.

Similar way you can use else statement with while loop.

The 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 (e.g., in stubs for example):

2.6 Importing Modules

Python function definition can, usefully, be stored in one or more separate files for easier maintenance and to allow them to beused in several programs without copying the definitions into each one. Each file storing  function definitions is called a “module” and the module name is the file name with “.py” extension.

Example:

Functions stored in the module are made available to a program using the Python import keyword followed by the module name. Although not essential, it is customary to put any import statements at the beginning of the program.

Imported functions can be called using their name dot -suffixed after the module name. For example, a “f1()” function from an imported module named “userdefined” can be called with userdefined.f1() .

Design a new Python module called user defined by defining all functions as illustrated below. Save the file as userdefined.py and run the file.

userdefined.py

Start a new script with name importexample.py (/ipynb). Next call each function with and without arguments as per the requirements. Run the program and get the output as illustrated below:

Importing Modules:

Python includes “sys” and “keyword” modules that are useful for interrogating the Python system itself. The keyword module contains a list of all Python keywords in its kwlist attribute and provides as iskeyword () method if you want to rest a word.

Performing Mathematics

Random

2.7 Ending a Program Early with sys.exit ()

2.8 Questions for Practice:

  1. What is Flow Chart ? Give the meaning of different flow chart symbols.
  2. Write a Flow chart and Python program for the following:
    • To find the average of two numbers.
    • To find the factorial of a given number N.
    • To find the simple interest given the value of P,T and R
    • To find the maximum of two numbersTo find the sum of first 50 natural numbers
  3. What are operators? Explain the following Operators with example:
    • Binary Boolean Operators: and, or & not
    • Compare == and = operator.
  4. What is Flow Control? Explain the different Elements of Flow Control?
  5. Define Block and explain what nested blocks with example are.
  6. Define condition control statement. Explain the different types of Condition Control Statement.
  7. Explain with flow chart and programming example , the following condition control statements :
    • if
    • if – else
    • nested if else
    • if – elif ladder
  8. What is iteration or looping ? Describe the different types of looping statements.
  9. Explain with syntax , flow chart and programming example the following looping operations.
    • While loop
    • For loop
  10. Discuss the working of range() function with programming example.
  11. Give the output of the following :
    • range(10)
    • range(1,11)
    • range(0,30,5)
    • range(0,-9,-1)
  12. What is infinite loop ? Explain with example.
  13. What are nested Loops ? Explain with examples.
  14. Discuss the following with examples :
    • break 
    • continue
    • else statement with loop
    • pass
  15. What are Python Modules ? Explain with examples how to import Python Modules .
  16. What is the difference between break and continue statements.
  17. What is the purpose of else in loop?
  18. Write logical expressions for the following :
    • Either A is greater than B or A is less than C
    • Name is Snehith and age is between 18 and 35.
    • Place is either Mysore or Bengaluru but not “Dharwad”.
  19. Convert the following while loop into for loop :

      x =10

     while (x<20):

            print(x+10)

           x+=2

21. Explain while and for loop . Write a program to generate Fibonacci series upto the given limit by defining FIBONACCI(n) function.

22. Mention the advantage of continue statement. Write a program to compute only even numbers sum within the given natural number using continue statement.

23. Demonstrate the use of break and continue keywords in looping structures using a snippet code.

24. With syntax explain the finite and infinite looping constructs in python. What is the break and continue statements .[ VTU June /July 2019]

Programming Questions for Practice:

  1. Construct a logical expressions to represent each of the following conditions :
    • Mark is greater than or equal to 100 but less than 70
    • Num is between 0 and 5 but not equal to 2
    • Answer is either ‘N’ or ‘n’
    • Age is greater than or equal to 18 and gender is male
    • City is either ‘Kolkata’ or ‘Mumbai’
  2. Write a program to check if the number of positive or negative and display an appropriate message.
  3. Write a program to convert temperature in Fahrenheit to Celsius.
  4. Write a program to display even numbers between 10 and 20.
  5. Write a program to perform all the mathematical operations of calculator.
  6. Write a program to accept a number and display the factorial of that number.
  7. Write a program to convert binary number to decimal number.
  8. Write a program to find the sum of the digits of a number.
  9. Write a program to display prime number between 30.
  10. Write a program to find the best of two test average marks out of three tests marks accepted from the user.
  11. Write a program to find the largest of three numbers . [ VTU June /July 2019]
  12. Write a program to check whether the given year is leap or not. [ VTU June /July 2019]
  13. Write a program to generate and print prime number between 2 to 50.
  14. Write a program to find those numbers which are divisible by 7 and multiple of 5 , between 1000 and 3000.
  15. Write a program to guess a number between 1 to 10.
  16. Write a program that accepts a word from the user and reverse it.
  17. Write a program to count the number of even and odd numbers from a series of numbers.
  18. Write a program that prints all the numbers from 0 to 10 except 3, 7 and 10.
  19. Write a program to generate Fibonacci series between 0 and 50.
  20. Write a program which iterates the integers from 1 to 50. For multiple of three print “Fizz” instead of the numbers and fro the multiples of five print “Buzz” . For numbers which are multiples of both three and five print “FizzBuzz”.
  21. Write a program that accepts a string and calculate the number of digits and letters.
  22. Write a program to check the validity of password input by users.
  23. Write a program to find the numbers between 100 and 400 where each digit of a number is an even number . The numbers obtained should be printed in a comma-separated sequence.
  24. Write a program to print alphabet patterns ‘A’ ,D, ‘E’, ‘G’,’L’, ‘T’ and ‘S’ with * symbol.
  25. Write a python program to create the multiplication table (from 1 to 20) of a number.
  26. Write a program to print the following patterns :

*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*

1

22

333

4444

55555

666666

7777777

88888888

999999999

*

* *

* * *

* * * *

* * * * *

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

A

B B

C CC

D DDD

E EEEE

* * * * *

* * * *

* * *

* *

*

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

        *

      * * *

    * * * * *

  * * * * * * *

* * * * * * * * *

        1

      2 3 2

    3 4 5 4 3

  4 5 6 7 6 5 4

5 6 7 8 9 8 7 6 5

* * * * * * * * *

  * * * * * * *

    * * * * *

      * * *

        *

           1

         1   1

       1   2   1

     1   3   3    1

    1  4    6   4   1

   1  5   10   10  5   1

1

2 3

4 5 6

7 8 9 10

######################################################################

References :