Python Module 2 Ktu Complete Notes
Python Module 2 Ktu Complete Notes
E
ALGORITHM AND PSEUDOCODE REPRESENTATION:- Meaning and Definition of
EG
Pseudocode, Reasons for using pseudocode, The main constructs of pseudocode - Sequencing,
selection (if-else structure, case structure) and repetition (for, while, repeat-until loops), Sample
problems
LL
INTRODUCTION
ALGORITHM
O
● An algorithm describes a systematic way of solving a problem.
C
● It is a step by step procedure that produces an output when given the necessary inputs.
● An algorithm uses pure English phrases or sentences to describe the solution to a problem.
G
● An algorithm itself is the division of a problem into small steps which are ordered in sequence
and easily understandable.
IN
● The same problem can be solved with different methods. So, for solving the same problem,
different algorithms can be designed.
R
An algorithm can be defined as “a complete, unambiguous, finite number of logical steps for
solving a specific problem.”
IN
Step 1 Identification of input: For an algorithm, there are quantities to be supplied called input and
these are fed externally. The input is to be identified first for any specified problem.
G
Step 2 Identification of output: From an algorithm, at least one quantity is produced, called for any
EN
specified problem.
Step 3: Identify the processing operations: All the calculations to be performed in order to lead to
output from the input are to be identified in an orderly manner.
Step 4: Processing Definiteness: The instructions composing the algorithm must be clear and there
EA
Characteristics of Algorithm
An algorithm must possess following characteristics:
1. Precision - the steps are precisely stated or defined.
2. Uniqueness - results of each step are uniquely defined and only depend on the input and the
result of the preceding steps.
Example 1
E
We can write an algorithm to evaluate an expression, say d = a + b ∗ c. Here a, b, c, and d are known
as variables. Algorithm for the expression evaluation.
EG
Algorithm_Evaluate(a,b,c)
Step 1: Start
LL
Step 2: Read the values of a, b and c.
Step 3: Find the product of b and c.
Step 4: Store the product in a temporary variable, temp.
O
Step 5: Find the sum of a and temp.
Step 6: Store the sum in d.
C
Step 7: Print the value of d.
Step 8: Stop.
Example 2
G
IN
To find simple interest ((SI=P*N*R)/100) where P-Principle amount, N-No. of years, R-Rate of
interestAdvantages and Disadvantages of Algorithm
R
EE
Algorithm_SimpleInterest(P,N,R)
Step 1: Start
Step 2: Read the three input quantities principal(P), rate(R) and years(N).
IN
Step 5: Stop.
EN
Advantages
● Effective Communication: Since algorithms are written in English like language, it is simple
to understand step-by-step solutions of the problems.
● Easy Debugging: Well-designed algorithms make debugging easy so that we can identify
EA
Disadvantages
● Developing algorithms for complex problems would be time consuming and difficult to
understand.
● Understanding complex logic through algorithms can be very difficult.
Representation of Algorithms
There are two common methods of representing an algorithm:-
● flowchart
● pseudocode
E
PSEUDOCODE
EG
● A pseudocode is a high-level representation of an algorithm that uses a mixture of natural
language and programming language-like syntax.
● It is more structured than an algorithm in that it uses mathematical expressions with English
LL
phrases.
● Also use programming constructs in a pseudocode which are not permitted in an algorithm in
a strict sense.
O
● Pseudocode is not a true program and thus is independent of any programming language.
C
Reasons for using pseudocode
G
1. Ease of understanding: Since the pseudocode is programming language independent, new
developers can also understand it very easily.
IN
2. Focus on logic: A pseudocode allows you to focus on the algorithm’s logic without bothering
about the syntax of a specific programming language.
3. More legible: Combining programming constructs with English phrases makes pseudocode
R
more legible and conveys the logic precisely.
EE
6. Identification of flaws: A pseudocode helps identify flaws in the solution logic before
implementation.
G
Example 1
EN
Pseudocode_Evaluate(a,b,c)
1. Start
EA
2. READ(a, b, c)
3. d = a + b ∗ c
4. PRINT(d)
M
5. Stop
K
Example 2
To find simple interest ((SI=P*N*R)/100) where P-Principle amount, N-No. of years, R-Rate of
interest
Pseudo_SimpleInterest(P,N,R)
1. Start
2. READ(P,N,R)
3. SI = (P*N*R)/100
4. PRINT(SI)
5. Stop
E
The main constructs of pseudocode
EG
A good pseudocode should follow the structured programming approach. Structured coding aims to
improve the readability of pseudocode by ensuring that the execution sequence follows the order in
which the code is written. Such a code is said to have a linear flow of control.
LL
Sequencing, selection (decision), and repetition (loop) are three programming constructs
that allow for linear control flow. These are also known as single entry – single exit constructs.
O
● In the sequence structure, all instructions in the pseudocode are executed (exactly) once without
skipping any.
C
● On the other hand, with selection and loop structures, it is possible to execute certain
G
instructions repeatedly or skip some. In such structures, the decision as to which statements are
to be executed or whether the execution should repeat will be determined based on testing a
IN
condition.
We use special symbols called relational operators to write such conditions. The various
relational operators are listed in the table given below. It is also possible to combine two
R
or more conditions using logical operators like “AND” (&&), “OR” (||). Eg: a > b AND a
EE
> c.
IN
G
EN
1. Sequence
EA
This is the most elementary construct where the instructions of the algorithm are executed in the order
listed. It is the logical equivalent of a straight line.
Consider the code below.
M
S1
S2
K
S3
.
.
Sn
The statement S1 is executed first, which is then followed by statement S2, so on and so forth, Sn until
all the instructions are executed. No instruction is skipped and every instruction is executed only once.
Example:- The pseudocode SimpleInterest used to find simple interest ((SI=P*N*R)/100) where P -
Principle amount, N - No. of years, R - Rate of interest
E
Pseudo_SimpleInterest(P,N,R)
1. Start
EG
2. READ(P,N,R)
3. SI = (P*N*R)/100
4. PRINT(SI)
LL
5. Stop.
2. Decision or Selection
O
A selection structure consists of a test condition together with one or more blocks of statements. The
C
result of the test determines which of these blocks is executed. There are mainly two types of
selection structure:-
A. if structure
G
IN
● simple if structure
R
● if else structure
● If else if else structure
EE
B. case structure
A. if structure
IN
if(condition)
TRUE_INSTRUCTIONS
EA
endif
If the test condition is evaluated to TRUE, the statements denoted by TRUE_INSTRUCTIONS are
executed. Otherwise, those statements are skipped.
M
Pseudo_CheckPositive(x)
1. Start
2. READ(x)
3. if(x > 0)
4. PRINT(x,“ is positive”)
5. endif
6. Stop
E
if(condition)
EG
TRUE_INSTRUCTIONS
else
FALSE_INSTRUCTIONS
LL
endif
This structure contains two blocks of statements. If the test condition is met, the first block (denoted
O
by TRUE_INSTRUCTIONS) is executed and the algorithm skips over the second block (denoted by
FALSE_INSTRUCTIONS). If the test condition is not met, the first block is skipped and only the
C
second block is executed.
G
IN
Pseudo_PersonType(age)
1. Start
R
2. READ(age)
3. if(age >= 18)
EE
7. endif
8. Stop
G
Pseudo_LargerTwo(a,b)
1. Start
EA
2. READ(a, b)
3. if (a > b)
4. large = a
M
5. else
6. large = b
K
7. endif
8. PRINT(large)
9. Stop
Pseudo_SmallestThree(a, b, c)
1. Start
2. READ(a, b, c)
3. if (a < b)
E
4. small = a
5. else
EG
6. small = b
7. endif
8. if (c < small)
LL
9. small = c
10. endif
11. PRINT(small)
O
12. Stop.
C
A.3 if else if else structure
When a selection is to be made out of a set of more than two possibilities, you need to use the if else
G
if else structure, whose syntax is given below:
IN
if(condition1)
TRUE_INSTRUCTIONS1
R
else if(condition2)
TRUE_INSTRUCTIONS2
EE
else
FALSE_INSTRUCTIONS
endif
IN
Example:- The pseudocode CompareVariables(x, y) compares two variables x and y and prints the
relation between them.
EA
Pseudo_CompareVariables(x, y)
1. Start
M
2. READ(x,y)
3. if(x > y)
K
9. endif
10. Stop
There is no limit to the number of else if statements, but in the end, there has to be an else statement.
The conditions are tested one by one starting from the top, proceeding downwards. Once a condition
is evaluated to be True, the corresponding block is executed, and the rest of the structure is skipped. If
E
none of the conditions are met, the final else part is executed.
EG
B. case structure
The case structure is a refined alternative to if else if else structure. The pseudocode representation of
LL
the case structure is given below. The syntax of case structure is:
caseof expression
O
case 1 value1:
BLOCK1
C
case 2 value2:
BLOCK2
G
.
.
IN
.
.
.
R
.
EE
.
case n valuen:
BLOCKn
default :
IN
DEFAULT_BLOCK
endcase
G
The case structure works like this: First, the value of expression is compared with value1. If there is a
EN
match, the first block of statements denoted as block1 will be executed. Each block will have a break
at the end which causes the case structure to be exited.
If there is no match, the value of the expression (or of the variable) is compared with value2. If there
EA
is a match here, block2 is executed and the structure is exited at the corresponding break statement.
This process continues until either a match for the expression value is found or until the end of the
cases is encountered. The DEFAULT_BLOCK will be executed when the expression does not match
M
If the break statement is omitted from the block for the matching case, then the execution continues
into subsequent blocks even if there is no match in the subsequent blocks, until either a break is
encountered or the end of the case structure is reached.
Example:- The pseudocode Print_Direction(n) prints the direction name based on the value of a
character, n.
Pseudo_PrintDirection(n)
1. Start
2. READ(n)
E
3. caseof n
4. case 'N':
EG
5. PRINT("North")
6. break
7. case 'E':
LL
8. PRINT("East")
9. break
10. case 'W':
O
11. PRINT("West")
12. break
C
13. case 'S':
14. PRINT("South")
15. break
16. default :
G
IN
17. PRINT("Invalid direction code")
18. endcase
19. Stop
R
3. Repetition or loop
EE
When a certain block of instructions is to be repeatedly executed, we use the repetition or loop
IN
construct. Each execution of the block is called an iteration. If the number of iterations (how many
times the block is to be executed) is known in advance, it is called definite iteration. Otherwise, it is
called indefinite or conditional iteration.
G
A. while loop
B. repeat-until loop
C. for loop
A. while loop
A while loop is generally used to implement indefinite iteration. The while loop is a conditional
construct that executes a block of statements again and again till the given condition remains TRUE.
Whenever the condition is evaluated FALSE then the loop will terminate. The general form/syntax of
the while loop is as follows:
E
Initialization of control variable
EG
while (condition)
TRUE_INSTRUCTIONS
Updation in control variable
LL
endwhile
O
Here, the loop body (TRUE_INSTRUCTIONS) is executed repeatedly as long as the condition
evaluates to TRUE. When the condition is evaluated as FALSE, the loop body is terminated.
C
Example:- The pseudocode PrintGeek(count) prints the statement “Hello Geek” 3 times.
Pseudo_PrintGeek(count)
G
IN
1. Start
2. READ(count = 0)
R
3. while(count < 3)
EE
4. count = count+1
5. PRINT("Hello Geek")
6. endwhile
7. Stop
IN
Example:- The pseudocode AverageAge1(age) to determine the average age of students in a class.
G
The user will stop giving the input by giving the age as 0.
EN
Pseudo_AverageAge1(age)
1. Start
2. sum = 0
EA
3. count = 0
4. READ(age)
5. while (age!=0)
M
8. READ(age)
9. endwhile
10. average = sum/count
11. PRINT(average)
12. Stop
B. repeat-until loop
The second type of loop structure is the repeat-until structure. This type of loop is also used for
indefinite iteration. Here the set of instructions constituting the loop body is repeated as long as the
condition evaluates to FALSE. When the condition evaluates to TRUE, the loop is exited.
E
The general form of repeat-until loop is shown below.
EG
repeat
FALSE_INSTRUCTIONS
Updation in control variable
LL
until (condition)
O
Example:- The pseudocode AverageAge2(age) to determine the average age of students in a class.
The user will stop giving the input by giving the age as 0.
C
Pseudo_AverageAgev2(age)
1. Start
G
IN
2. sum = 0
3. count = 0
4. READ(age)
R
5. repeat
6. sum = sum + age
EE
7. count = count + 1
8. READ(age)
9. until (age == 0)
IN
12. Stop
EN
There are two major differences between while and repeat-until loop constructs:
1. In the while loop, the pseudocode continues to execute as long as the resultant of the condition is
TRUE; in the repeat-until loop, the looping process stops when the resultant of the condition becomes
EA
TRUE.
2. In the while loop, the condition is tested at the beginning; in the repeat- until loop, the condition is
M
For this reason, the while loop is known as an entry controlled loop and the repeat-until loop is
known as an exit controlled loop.
C. for loop
The for loop implements definite iteration. There are three variants of the for loop. All three for loop
constructs use a loop variable as a counter that starts counting from a specific value called begin and
updates the loop variable after each iteration. The loop body repeats execution until the loop variable
value reaches end value. The first for loop variant can be written in syntax in python as follows:
E
for var = begin to end
EG
LOOP_INSTRUCTIONS
endfor
LL
Here, the loop variable, var is first assigned with the value begin (var=begin). Then the condition
var <= end is tested. If the outcome is TRUE, the loop body is executed. After the first iteration, the
loop variable is incremented by 1 (var=var+1). The condition var <= end is again tested with the
O
updated value of var and the loop body is again executed, if the condition evaluates to TRUE. This
C
process of updating the loop variable after an iteration and proceeding with the execution if the
condition evaluates to TRUE continues until the var value becomes greater than end (var>end). At
that time, the condition evaluates to FALSE and the loop execution stops.
G
EXAMPLE:- The pseudocode Factorial(n) to find the factorial of a number.
IN
Pseudo_Factorial(n)
R
1. Start
2. READ(n)
EE
3. fact = 1
4. for var = 1 to n
5. fact = fact ∗ var
IN
6. endfor
7. PRINT(fact)
G
8. Stop
EN
In the second for loop variant, whose syntax is given above, the loop variable is decremented 1 after
every iteration. And the condition being tested is var >= end. Here, begin should be greater than or
equal to end, and the loop exits when this condition is violated.
EA
EXAMPLE:- The pseudocode PrintDown to print the numbers from 1 to 50 in descending order
K
Pseudo_PrintDown
1. Start
2. for count = 50 downto 1
3. PRINT(count)
4. endfor
5. Stop
E
Pseudo_Factorial(n)
EG
1. Start
2. READ(n)
3. fact = 1
LL
4. for var = n downto 1
5. fact = fact ∗ var
6. endfor
O
7. PRINT(fact)
8. Stop
C
It is also possible to update the loop variable by an amount other than 1 after every iteration. The
value by which the loop variable is increased or decreased is known as step. In the syntax shown
G
below, the step value is specified using the keyword by .
IN
for var = begin to end by step
LOOP_INSTRUCTIONS
R
endfor
EE
1 till it reaches 10
EN
E
FLOWCHARTS
EG
A flowchart is a diagrammatic representation of an algorithm that shows how control flows in
it. Flowcharts are composed of various blocks interconnected by flow-lines. Each block in a
flowchart represents some stage of processing in the algorithm. Different types of blocks are defined
LL
to represent the various programming constructs of the algorithm.
Flow lines indicate the order in which the algorithm steps are executed. The flow lines
O
entering a block denote data (or control) flow into the block and the flow lines emerging from a block
denote data (control) outflow.Most blocks have only single incoming and outgoing flow lines. The
C
exception is for blocks representing selection and loop constructs. Such blocks have multiple exits,
one for each possible outcome of the condition being tested and each such outcome is called a branch.
G
IN
Table below lists some commonly used flowchart symbols and their descriptions.
R
Flowchart symbol Description
EE
E
Flowlines are indicated by arrows to show the direction of data
flow. Each flowline connects two blocks.
EG
This indicates an on-page connector. This is used when one part of
a long flowchart is drawn on one column of a page and the other
part in the other column of the same page.
LL
This indicates an off-page connector. This is used when the
O
flowchart is very long and spans multiple pages.
C
G
Solved problems - Algorithms and Flowcharts
IN
1. To find simple interest.
R
EE
IN
G
EN
EA
M
K
E
EG
LL
O
C
G
IN
3. Flowchart to evaluate the expression d=a+b*c
R
EE
IN
G
EN
EA
M
K
E
EG
LL
O
C
G
IN
R
5. Flowchart to find whether the given number is even or odd.
EE
IN
G
EN
EA
M
K
E
EG
LL
O
C
G
IN
R
EE
IN
G
EN
EA
M
K
E
EG
LL
O
C
G
IN
R
EE
IN
G
EN
EA
M
K
E
EG
LL
O
C
G
IN
R
EE
IN
G
EN
EA
M
K
E
EG
LL
O
C
G
IN
R
EE
IN
G
EN
EA
M
K
E
EG
LL
O
C
G
IN
R
EE
IN
G
EN
EA
M
K