0% found this document useful (0 votes)
16 views

UNIT 2-1

This document covers Python programming concepts related to control flow, including conditional statements (if, else, elif) and loops (for, while). It explains how to implement decision-making in programs and how to execute repetitive tasks using loops, with examples for clarity. The content is aimed at enhancing proficiency in handling strings and functions in Python.

Uploaded by

Aarush Chauhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

UNIT 2-1

This document covers Python programming concepts related to control flow, including conditional statements (if, else, elif) and loops (for, while). It explains how to implement decision-making in programs and how to execute repetitive tasks using loops, with examples for clarity. The content is aimed at enhancing proficiency in handling strings and functions in Python.

Uploaded by

Aarush Chauhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Department of Computer Science

IMS Engineering College

UNIT – 2
PYTHON PROGRAM CONTROL FLOW AND CONDITIONAL
BLOCKS

Course Outcome: Express proficiency in the handling of strings and functions.

Topic Coverage
If, Else and Else If, Simple loops in Python, For loop using range function, string, list and
dictionary. Use of while loop in Python. Loop manipulation using pass, continue, break and else.
Programming using Python conditional and loop blocks.

INTRODUCTION
Writing code for any problem requires writing instructions that is executed by computer
system. Easy problem requires writing sequential instruction, for example, writing code for
adding two numbers require accepting two numbers from user and adding them by using
arithmetic operator.
However, real life problems usually require non-sequential instructions i.e., the flow of
program can be decided by one of several options available to user. For example, while
operating on ATM machine, user see several options, checking the balance, withdrawal of
money, changing ATM pin and so on. All these options have some kind of programming behind
them and the flow of the program is decided by the option opt by the user. For this programming
languages provide decision statements.
Apart from non-sequential statements, sometimes repetitive execution of statements is
required in the program. For example, to store the information about the marks of five subjects
of students, the input statement (that reads the marks of the student) needs to be executed
repetitively. For this, programming languages provide loops. In this unit, we will discuss about
the decision statements and loops provided by Python.

IF CONDITIONAL STATEMENT
First decision statement supported by Python is if conditional statement. If conditional
statement decides the flow of the program on the basis of the condition provided. The
statement/s written in if block are executed when the condition is true. If condition executes to
be false, the statement/s written in if block are skipped and control of the program is transferred
to the statement written after the if block.

Syntax of the if conditional statement is:


if <condition>:
statement/s to be executed

Python Programming 1 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Let’s understand it with the help of an example. Suppose you want to build an application
which requires to check whether a person is eligible to vote or not. In India, if a person is of 18
years or above, then the person is eligible to vote otherwise not.

For writing the code for this application, the input for the application should be age and the if
conditional statement should check this age whether it is greater than or equal to 18 or not.

The program for this application can be written as:

We have used three built-in functions int( ), input( ) and print( ) in the above code. The usage
of these functions is as follows:
i. input( ): this function is used to accept any input value from user. By default, the
input( ) function returns string values i.e., it read any value (even if it is a number)
as string.
ii. int( ): this function is used to convert the values in to integer data type.
iii. print( ): this function displays the message given in quotes on the output device.

The output of the above program will be:

This code will work fine till the condition is true i.e., for all values greater than or equals to 18,
the program will give the output. But, for the values less than 18, the program will not produce
any output, because there is no statement after the if block.

Hence, the code can be modified as:

Now, if any value less than 18 will be entered by user, the program will produce the output.

The output will be as follows:

Python Programming 2 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

But, there is still something wrong with the code. The last print statement will be executed even
if the user will enter the age that is greater than or equal to 18. Let’s have a look at it.

This is because any statement written after if block will execute (in both cases, when condition
is true or false) as part of sequential instruction. But we want to give the sorry message to the
user when the if block statement will not execute due to condition being false.

For that only if conditional statement is not sufficient. We need to use if-else conditional
statement.

IF ELSE CONDITIONAL STATEMENT

In if-else conditional statement, if block statement/s are executed when the condition turns to
be true, otherwise else block statement/s are executed. The syntax of if-else statement is:
if <condition>:
statement/s to be executed
else:
statement/s to be executed

The above code can be modified using if-else conditional statement as:

The output for both the cases when user enters age greater than or equal to 18 and for the
case when the age is less than 18 are as follows:

Python Programming 3 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

IF ELIF ELSE CONDITIONAL STATEMENT


In certain cases, only one condition is not sufficient to decide the flow of the program. It is
required to specify multiple conditions but out of these only one condition decide the flow of
the program i.e., only one condition turns out to be true at a particular time. When the program
requires to express multiple condition, then if-elif-else conditional statement is used. As we
have already seen, we can not specify condition with else block, so multiple conditions are
expressed with the help of if and elif blocks.

The syntax of if-elif-else conditional statement is:

if <condition 1>:
statement/s to be executed
elif <condition 2>:
statement/s to be executed
elif <condition 3>:
statement/s to be executed
elif <condition n>:
statement/s to be executed
else:
statement/s to be executed

The program execution will take place as: ‘condition 1’ will be checked first, if it turns to be
true, then the statement written in this block will be executed and the control of the program
will be transferred to the statement written after else block, otherwise the next condition
‘condition 2’ will be checked and so on. If none of the conditions specified turns to be true,
then the statements written in else block will be executed.

Although it is possible to specify multiple conditions by using multiple if conditional


statements but the difference between using multiple if and if-elif is that in case of multiple if
conditional statement, even if the first condition is true, the remaining conditions will be
checked that lead to increase in execution time (if the program contains many conditions),
while in case of if-elif conditional statement, if first condition turns to be true, the statements
written in that block are executed and rest of the conditions are not checked which saves
execution time.

Example, suppose you want to develop an application that accepts the marks of the student and
tell the grade. Now the marks can fall in different ranges and accordingly grades are decided.

Python Programming 4 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

However, the marks will fall only in one range i.e., there will be multiple conditions to check
that in which range marks fall but only one condition will be true. Hence, using if-elif-else
conditional statement is suitable to develop this application.

The code for this problem can be written as:

The output for various marks range is:

NESTED IF ELSE CONDITIONAL STATEMENT

Many times, the program involves multiple conditions but to reach to the desired output all the
conditions needs to be true. For example, consider an application that tells whether you are

Python Programming 5 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

eligible for taking loan or not. The application ask for certain values such as salary, credit score,
information about any other loan and so on. After checking all the values, the application can
tell whether you are eligible to take loan or not.

In such scenarios, nested if-else conditional statement can be used. Nested means one if
conditional statement containing another if conditional statement.

The syntax of nested if-else conditional statement is:

if <condition 1>:
if <condition 2>:
if <condition 3>:
statement/s to be executed
else:
statement/s to be executed
else:
statement/s to be executed
else:
statement/s to be executed

There is an else block associated with each if block. If condition 1, condition 2 and condition
3 will be true then the statement/s written inside if block will execute. However, if any of the
condition will be false, then the statement/s written in its associated else block will be executed.

Let’s implement the loan application program. The code for it can be written as:

The output of the above program will be:

Python Programming 6 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

So, for the cases where multiple conditions need to be given but all the conditions should be
true, nested if-else conditional statements are suitable.

FOR LOOP

In loops, statement/s are executed repetitively until the condition becomes False. Loop has a
starting point and continuously execute statement/s written in the block till the end value is
reached. for loop is used in scenarios when the programmer already knows that how many time
the loop is required to execute.

The syntax of the for loop is:


for variable in <sequence>:
statement/s to be executed

The sequence in the syntax of for loop can be any sequence, such as, sequence generated by
range( ) function, string, list, set, tuple and dictionary.

For Loop using range ( ) function

range( ) Function

range ( ) function generates a sequence of integers. Syntax of the range ( ) function is:
range (start, end, increment)

range ( ) function produces a sequence of integers from start up to end (but not including end)
in steps of increment.

Python Programming 7 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

The only mandatory argument of range function is end. If value of increment is not specified
then it is assumed to be 1. If value of start is not specified then it is assumed to be 0.

Values of start, end, increment should be of integer type only. Any other type of value will
result in error.

Following table represent examples on how to use range ( ) function with for loop.

range ( ) Function with for loop Output

For Loop Example: if an application needs to be implemented that calculates the sum of first
10 integers, then for loop can be used as:

The output of this code segment will be:

The above code segment accepts a value from the sequence generated from range( ) function,
assign this value to variable i and adds it to variable s. The statement for adding the value of
variable s into variable I will execute automatically till the last value of the sequence generated

Python Programming 8 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

from range( ) function.

For Loop using String

A string is a sequence of characters. Single quotes or double quotes can be used to represent
string. Multi-line strings can be represented using triple quotes. This sequence can be used at
the place of range ( ) function with the for loop.

Example

This example initialize the variable name with a string. When string is processed by loop, each
character of the string is treated as a separate element. So, character of the string will be
assigned one by one to the variable i and printed.

The output of this code will be:

Suppose, you want to compute the length of the string, then it can be done by using string as a
sequence with for loop.

The output of this code will be:

For Loop using List

A list is an ordered sequence of heterogeneous items (items with different data types) enclosed
in square brackets. This sequence can be used at the place of range ( ) function with for loop.

Example

Python Programming 9 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Consider a list, list1 = [10, 20.5, “abc”, “xyz”]

When list is processed by loop, each element separated by comma will be assigned one by one
to the variable i and printed.

The output of this code will be:

When list contains string, then it is treated as a single element and printed as a word/sentence,
not character by character.
To access the individual characters of the string (given in the list), we need to use nested loop.
For example, consider a list, names = [“John”, “Stephen”, “Eva”, “Reva”]. If we want to print
only those names whose length is more than 3, then we need to use nested loop.

Elements of the list will be assigned one by one to the variable i and the inner loop will process
the string character by character and compute the length of each string defined as element in
the list.

The output of the above code will be:

Python Programming 10 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

For Loop using Tuple

A tuple is also an ordered collection of heterogeneous items but enclosed in brackets. Tuple
with elements can be created by defining elements within a pair of brackets. A tuple containing
only one element is called singleton tuple and is defined by attaching a comma with the
element. If comma is not attached with element then the element is considered as int or float.

The way list is used as sequence, tuple can also be used.

Consider the tuple, tuple1 = (40, 32.5, “abc”, “xyz”)

The output of the above code will be:

Similar to list, string can be an element of the tuple and will be processed in the similar way.

For example, consider a tuple names = (“John”, “Stephen”, “Reva”, “Eva”)

The output of the above code will be:

For Loop using Set

A set is a collection of unique elements that are not in a particular order. Set in Python is

Python Programming 11 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

represented within a pair of curly braces. No index is attached with the set elements.

Similar to list and tuple, sets can also be used as a sequence with for loop. However, the output
of the sequence can come in any order because it is unordered collection.

For example, consider a set, marks = {78, 93, 88, 95}.

When set is processed by loop, each element separated by comma will be assigned one by one
to the variable i and printed. However, the elements can be assigned and printed in any order.

The output of the above code will be:

Similar to list and tuple, string can be an element of the set and will be processed in the similar
way.

For example, consider a set names = {“John”, “Stephen”, “Reva”, “Eva”}

The output of the above code will be:

For Loop using Dictionary

A dictionary is an unordered collection of key-value pairs, enclosed within a pair of curly


Python Programming 12 HUNNY GAUR
(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

brackets. The key-value pairs are separated by comma. The values in the dictionary are
accessed by their keys. However, keys cannot be accessed by using the values. Keys in the
dictionary are similar to the indexes in the sequence. Dictionary with elements can be created
by defining elements (key-value pair) within a pair of curly brackets.

A dictionary can also be used as a sequence with for loop. Consider a dictionary that stores the
marks of the students:
marks = {“Alwin” : 87, “Myra” : 97, “Joel” : 90, “Mayand” : 88}

The output of the above code will be:

When dictionary is processed by loop, its keys are assigned to the loop variable. To access the
values associated with keys, keys need to be used as index with dictionary variable.

The output of this code will be:

Here variable i is printing the keys of the dictionary and marks[i] is printing the values
associated with dictionary.

WHILE LOOP

The same code segment can be executed by using while loop. However, while loop is more
appropriate to use with the scenarios when the programmers are not aware that how many times
the loop needs to be executed.

Python Programming 13 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

The syntax of the while loop is:


while <test condition>:
statement/s to be executed

For example, instead of calculating sum of first 10 integers, the application requires calculating
sum of integers entered by user. The termination of the loop will be considered when user will
enter zero (0).

The code for this problem can be written using while loop as:

The output will be:

The program will keep asking the numbers from user until the user will enter 0 and the loop
will be terminated.

NESTED LOOPS

When a loop is used inside another loop then it is called nested loop. Nested loops are mainly
used for printing two-dimensional data i.e., data which is represented in rows and columns.
The outer loop works for rows and inner loop works for columns.

The syntax of the nested for loop is:

for variable1 in <sequence>:


for variable2 in <sequence>:
statement/s to be executed

For example, consider an application that requires printing following pattern:

Python Programming 14 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

The code for the above pattern can be written using nested for loop as:

The pattern requires printing 4 rows and 4 columns but in each row the number of columns
being printed are equal to the row number. Therefore, the outer loop (that works for rows) will
run four times for the sequence values 1, 2, 3 and 4. And the inner loop (that works for columns)
will run 1, 2, 3 and 4 times for row 1, row 2, row 3 and row 4, respectively.

The additional blank print statement after coming out from the inner loop will help in changing
the row, once all column values will be printed. The print statement by default ends with new
line, therefore, a blank print statement will move the cursor to the new line. Also, while printing
the values of a specific row, all the column values should be printed in the same line. This
requires changing the default behaviour of the print statement that end the statement with new
line. To do so, end argument has been used in the print statement of the inner loop. The end
argument specify here that print statement should end with a space, not with the new line.

LOOP MANIPULATION USING BREAK, CONTINUE, PASS AND ELSE


STATEMENT
Sometimes we need to alter the normal flow of a loop in response to the occurrence of an event.
In such a situation, we may either want to exit the loop or continue with the next iteration of
the loop skipping the remaining statements in the loop.

Break Statement

The break statement enables us to exit the loop and transfer the control to the statement
following the body of the loop.

Continue Statement

The continue statement is used to transfer the control to next iteration of the loop. When the
continue statement is executed, the code that occurs in the body of the loop after the continue
statement is skipped.

Example demonstrating break and continue statement

In this example, we want to compute the overall percentage of marks obtained by a student. As
the number of subjects on which examination was conducted is not known beforehand, while

Python Programming 15 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

loop is used. When the while loop is executed, the user is prompted to enter the marks obtained
in different subjects. If the use responds with a null string (press enter), the break statement is
executed which results in termination of the loop, and the control moves to line number 19
(outside loop) for computation of percentage. However, if the marks entered by the user are
outside the range i.e., less than 0 and greater than 100, the user is prompted again to enter
marks. Thus, in the case of invalid marks, the use of continue statement makes it possible to
skip the statement that appear after the continue statement in the while loop and continue with
the next iteration of the loop for taking the next input from the user.

The output of the above code will be:

Pass Statement

Sometimes we may want to leave out the details of the computation in a function body, to be
filled in at a later point in time. The pass statement lets the program to go through this piece of
code without executing any code. It is just like a null operation. Often pass statement is used
as a reminder for some code, to be filled in later.

Python Programming 16 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Example

If a merchant wants to sell clothes and thinking about giving some discount at some later point
of time. So, the developer can design the code for discount using pass statement, to be used
later.
The following code-segment has a function sellingPrice that calls the function discount. As the
code for discount function just comprises a pass statement, it produces None as the return value.
Accordingly, the function sellingPrice ignores the value None returned by the function discount
and return price as the selling price.

The output of the above code will be:

If the pass statement is replaced by comment, then interpreter will detect it as an error “expected
an indented block after function definition” and will not let the code execute.

Python Programming 17 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

The output of this code will be:

Suppose now merchant wants to give 10% discount on clothes. So, we can easily modify the
discount function to apply 10% discount and rest of the code will remain same.

The output of the above code will be:

Else Statement

The else clause is useful in such situations where we may want to perform a task only on
successful execution of a for/while loop. The statements specified in else clause are executed
on normal termination of loop. However, if the loop is terminated forcibly using break
statement, then the else clause is skipped.

Example

Python Programming 18 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

This example uses the else clause for testing whether a given number is prime or not. A number
is said to be prime if and only if it has no divisor other than one and itself. The for loop given
in the code below checks for each number in the range (2, n) whether it is a divisor of n. If the
entire sequence is exhausted and no divisor of n is found, it is a prime number. In the function
Prime, if n is 1, then function will return False, indicating that the number is not prime. Inside
the for loop, if we find a divisor i of n in the range (2, n), the condition n%i == 0 becomes
True, indicating that the number is not prime. So, we set flag = False and exit the for loop.
However, if the for loop executes smoothly, we set flag = True indicating that number is prime
and flag is returned as the value of the function.

The output of the above code will be:

Python Programming 19 HUNNY GAUR


(BCC302) Assistant Professor

You might also like