Professional Documents
Culture Documents
Programming with
Python
ss
re
yP
As per Anna University syllabus - GE8151
sit
er
iv
Un
REEMA THAREJA
Assistant Professor
d
Published in India by
Oxford University Press
Ground Floor, 2/11, Ansari Road, Daryaganj, New Delhi 110002, India
ss
prior permission in writing of Oxford University Press, or as expressly permitted
by law, by licence, or under terms agreed with the appropriate reprographics
re
rights organization. Enquiries concerning reproduction outside the scope of the
above should be sent to the Rights Department, Oxford University Press, at the
yP
address above.
ISBN-13: 978-0-19-948949-7
er
ISBN-10: 0-19-948949-1
iv
Computers are so widely used in our day-to-day lives that imagining a life without them has become almost
impossible. They are not only used by professionals but also by children for interactively learning lessons,
playing games, and doing their homework. Applications of the computer and its users are increasing by
the day. Learning computer and programming basics is a stepping stone to having an insight into how the
machines work. In-depth knowledge of basic computing terminologies and problem solving strategies such as
algorithm, flowchart, and pseudocode are very essential to develop efficient and effective computer programs
that may help solve a user’s problems.
ss
Since computers cannot understand human languages, special programming languages are designed for
re
this purpose. Python is one such language. It is an open-source, easy, high-level, interpreted, interactive,
object-oriented and reliable language that uses English-like words. It can run on almost all platforms
yP
including Windows, Mac OS X, and Linux. Python is also a versatile language that supports development of
a wide range of applications ranging from simple text processing to WWW browsers to games. Moreover,
programmers can embed Python within their C, C++, COM, ActiveX, CORBA, and Java programs to give
sit
'scripting' capabilities to the users.
Python uses easy syntax and short codes as well as supports multiple programming paradigms, including
er
object oriented programming, functional Python programming, and parallel programming models. Hence, it
iv
has become an ideal choice for the programmers and even the novices in computer programming field find it
easy to learn and implement. It has encompassed a huge user base that is constantly growing and this strength
Un
of Python can be understood from the fact that it is the most preferred programming language in companies
such as Nokia, Google, YouTube, and even NASA for its easy syntax and short codes.
d
This book is designed as a textbook to cater to the requirements of the Python programming course offered to
the first year engineering students of Anna University. The objective of this book is to introduce the students
xf
to the fundamentals of problem solving strategies and the concepts of Python programming language, and
O
• Provides numerous programming examples along with their outputs to help students master the art of
writing efficient Python programs.
• Includes notes and programming tips to highlight the important concepts and help readers avoid common
programming errors.
• Offers rich chapter-end pedagogy including plenty of objective-type questions (with answers), review
questions, programming and debugging exercises to facilitate revision and practice of concepts learnt.
• Includes 6 Annexures and 5 appendices covering differences between Python 2.x and 3.x, installing
Python, debugging and testing, iterators, generators, getters, setters, @property, @deleter, Turtle graphics,
plotting graphs, additional illustrative examples, lab exercises, GUI and Web Programming provided to
supplement the text. Exercises are also added at the end of several annexures and appendices.
• Includes lab exercises and additional illustrative examples explained through algorithms and flowcharts
to help readers hone their logical and programming abilities.
• Provides case studies on creating calculator, calendar, hash files, compressing strings and files, image
ss
processing, shuffling a deck of cards, and mail merge that are linked to various chapters to demonstrate the
application of concepts.
re
• Contains 1 solved previous year's question paper and 2 solved model question papers included to help
readers prepare for the semester-end university examinations.
yP
• Point-wise summary and glossary of keyterms to aid quick recapitulation to concepts.
sit
Organization of the Book
The book contains 10 chapters, 6 annexures, 7 case studies, and 5 appendices. The details of the book are
er
presented as follows.
Chapter 1 discusses the various strategies used for problem solving. Topics such as algorithms, flowcharts,
iv
and pseudocodes supported with some illustrative problems are covered in this chapter.
Un
Chapter 2 discusses about programming languages and their evolution through generations. It describes
different programming paradigms, features of OOP, and merits and demerits of object oriented programming
languages. The chapter also gives a comparative study Python and other OOP languages, and highlights the
d
Chapter 3 details the history, important features and applications of Python. It also presents the various
building blocks (such as keywords, identifiers, constants variables, operators, expressions, statements and
xf
The chapter is followed 3 annexures – Annexure 1 provides instructions for installing Python. Annexure 2
provides the comparison between Python 2.x and Python 3.x versions. Annexure 3 discusses testing and
debugging of Python programs using IDLE.
Chapter 4 deals with the different types of decision control statements such as selection/ conditional
branching, iterative, break, continue, pass, and else statements.
Case studies 1 and 2 on simple calculator and generating a calendar show the implementation of concepts
discussed in Chapters 3 and 4.
Chapter 5 provides a detailed explanation of defining and calling functions. It also explains the important
concepts such as variable length arguments, recursive functions, modules, and packages in Python.
Annexure 4 explains how functions are objects in Python. Case study 3 on shuffling a deck of cards
demonstrates the concepts of functions as well as recursion.
Chapter 6 unleashes the concept of strings. The chapter lays special focus on the operators used with
strings, slicing operation, built-in string methods and functions, comparing and iterating through strings, and
the string module.
Chapter 7 discusses how data can be stored in files. The chapter deals with opening, processing (like
reading, writing, appending, etc.), and closing of files though a Python program. These files are handled in
text mode as well as binary mode for better clarity of the concepts. The chapter also explains the concept of
file, directory, and the os module.
Case studies 4, 5, and 6 on creating a hash file, mail merge, and finding the resolution of an image
demonstrate the applications of concepts related strings and file handling.
Chapter 8 details the different data structures (such as list, tuple, dictionary, sets, etc.) that are extensively
used in Python. It deals with creating, accessing, cloning, ad updating of lists as well as list methods and
functions. It also describes functional programming and creating, accessing, and updating tuples. It also
includes the concepts related to sets, dictionaries, nested lists, nested tuples, nested sets, nested dictionaries,
list comprehensions, and dictionary comprehensions.
Annexure 5 discusses the concepts of iterator and generator.
Chapter 9 introduces the concept of classes, objects, public and private classes, and instance variables. It
also talks about special methods, built-in attributes, built-in methods, garbage collection, class method, and
static method.
ss
Annexure 6 discusses the getter and setter methods as well as @property and @deleter decorators
facilitate data encapsulation in Python.
re
Chapter 10 elucidates the concepts of exception handling that can be used to make your programs robust.
Concepts such as try, except, and finally blocks, raising and re-raising exceptions, built-in and user-defined
yP
exceptions, assertions, and handling invoked functions, used for handling exceptions are demonstrated in
this chapter.
sit
Case study 7 shows how to compress strings and files using exception handling concepts.
The 5 appendices included in the book discuss about additional illustrative examples, lab exercises, GUI
er
programming, usage of Turtle graphics, plotting graphs and web programming in Python.
iv
Online Resources
Un
For the benefit of faculty and students reading this book, additional resources are available online at india.
oup.com/orcs/9780199489497.
d
For Faculty
or
For Students
• Lab exercises
• Test generator
• Projects
• Solutions to find the output and error exercises
• Extra reading material on unit testing in Python, sorting and searching methods, multi-threaded
programming, network programming, event-driven programming and accessing databases using Python
Acknowledgements
The writing of this textbook was a mammoth task for which a lot of help was required from many people.
Fortunately, I have had wholehearted support of my family, friends, and fellow members of the teaching staff
and students at Shyama Prasad Mukherji College, New Delhi.
My special thanks would always go to my parents, Mr Janak Raj Thareja and Mrs Usha Thareja, and
my siblings, Pallav, Kimi, and Rashi, who were a source of abiding inspiration and divine blessings for me.
I am especially thankful to my son, Goransh, who has been very patient and cooperative in letting me realize
my dreams. My sincere thanks go to my uncle, Mr B.L. Theraja, for his inspiration and guidance in writing
this book.
I would like to acknowledge the technical assistance provided to me by Mr Mitul Kapoor. I would like to
thank him for sparing out his precious time to help me to design and test the programs.
I would like to express my gratitude to the reviewers for their valuable suggestions and constructive
feedback that helped in improving the book.
Prof. M V S V Kiranmai
University College of Engineering, JNTU Kakinada
Dr Nagender Kumar Suryadevara
Geethanjali College of Engineering and Technology, Hyderabad
Dr Vipul Kumar Mishra
School of Engineering, Bennett University, Greater Noida, U.P.
Dr G Shobha
ss
R V College of Engineering, Bengaluru
Prof. Priyang P Bhatt
re
GH Patel College of Engineering and Technology, Vallabh Vidyanagar, Gujarat
yP
Prof. Karthick Nanmaran
School of Computing, SRM University, Chennai
Prof. Vinu S.
sit
St. Joseph's College of Engineering, Chennai, Tamil Nadu
er
Last but not the least, I would like to thank the editorial team at Oxford University Press, India for their
help and support over the past few years.
iv
Comments and suggestions for the improvement of the book are welcome. Please send them to me at
Un
reemathareja@gmail.com.
Reema Thareja
d
or
xf
O
1 Algorithmic Problem Solving 1
2 Introduction to Object Oriented Programming (OOP) 26
ss
3 Basics of Python Programming 46
Annexure 1 — Installing Python 88
re
Annexure 2 — Comparison between Python 2.x and Python 3.x Versions 90
Annexure 3 — Testing and Debugging 93
yP
4 Decision Control Statements 100
Case Study 1 — Simple Calculator 143
sit
Case Study 2 — Generating A Calendar 146
er
Case Study 4 — Creating a Hash File (or a message digest of a file) 278
or
ss
2.3 Programming Paradigms 32
(Instructions, State, Control Flow, 2.3.1 Monolithic Programming 32
re
Functions) 2 2.3.2 Procedural Programming 32
1.3.1 Different Approaches of 2.3.3 Structured Programming 33
yP
Designing an Algorithm 2 2.3.4 Object Oriented Programming
1.4 Algorithmic Problem Solving (OOP) 34
Steps 3
sit
2.4 Features of Object Oriented
1.5 Simple Strategies and Notations for Programming 35
Developing Algorithms 4
er
2.4.1 Classes 35
1.5.1 Control Structures Used in 2.4.2 Objects 36
iv
2.4.4 Inheritance 37
1.5.3 Pseudocodes 11 2.4.5 Polymorphism 38
1.5.4 Programming Languages 13 2.4.6 Containership 38
1.6 Illustrative Problems 14
d
2.4.7 Reusability 38
1.6.1 Find Minimum in a List 14
or
2.4.8 Delegation 39
1.6.2 Insert a Card in a List of Sorted 2.4.9 Data Abstraction and
xf
Cards 16 Encapsulation 39
1.6.3 Guess an Integer Number in a 2.5 Merits and Demerits of Object
O
ss
3.12.1 Arithmetic Operators 62 4.7 The Pass Statement 134
3.13.2 Comparison Operators 63 4.8 The Else Statement Used with
re
3.12.3 Assignment and in-Place or Loops 135
Shortcut Operators 64 Case Study 1 — Simple Calculator 143
yP
3.12.4 Unary Operators 65 Case Study 2 — Generating
3.12.5 Bitwise Operators 65 A Calendar 146
sit
3.12.6 Shift Operators 66
3.12.7 Logical Operators 66 5 Functions and Modules 148
er
Associativity 68
5.3 Function Call 152
3.13 Expressions in Python 69
5.3.1 Function Parameters 152
3.14 Operations on Strings 69
5.4 Variable Scope and Lifetime 154
d
3.14.1 Concatenation 70
5.4.1 Local and Global Variables 155
or
ss
Annexure 4 — Functions as Objects 200
7.5.2 append() Method 256
Case Study 3 — Shuffling A Deck of
re
7.5.3 The read() and readline()
Cards 202
Methods 257
yP
7.5.4 Opening Files Using with
6 Python Strings Revisited 203
Keyword 259
Introduction 203 7.5.5 Splitting Words 260
sit
6.1 Concatenating, Appending, and 7.5.6 Some Other Useful File
Multiplying Strings 204 Methods 261
er
6.3 String Formatting Operator 207 7.7 Renaming And Deleting Files 264
6.4 Built-in String Methods And 7.8 Directory Methods 265
Un
6.6 ord() and chr() Functions 218 Case Study 5 — Mail Merge Program 280
Case Study 6 — Finding Resolution of an
xf
ss
Values 311
9.4 The __init__() Method (The Class
8.3.9 Nested Tuples 312
Constructor) 364
re
8.4.10 Checking The Index: index()
9.5 Class Variables And Object
Method 312
yP
Variables 364
8.4.11 Counting The Elements: count()
9.6 The __del__() Method 367
Method 313
9.7 Other Special Methods 368
sit
8.4.12 List Comprehension and
9.8 Public And Private Data
Tuples 313
Members 369
er
ss
Solved Model Question Paper - 1 483
re
Solved Model Question Paper - 2 485
About the Author 487
yP
sit
er
iv
Un
d
or
xf
O
ss
Examples
re
1.1 INTRODUCTION
yP
sit
A program is a set of instructions that tells the computer how to solve a particular problem. Various program
design tools like algorithms, pseudocdes and flowcharts are used to design the blueprint of the solution
er
(or the program to be written). Computer programming goes a step further in problem solving process.
Programming means writing computer programs. While programming, the programmers take an algorithm
iv
and code the instructions in a particular programming language so that it can be executed by a computer.
Un
These days, there are many programming languages available in the market. The programmer can choose any
language depending on his expertise and the problem domain.
The following sections will deal with different program design tools, knowledge of which is compulsory
d
1.2 ALGORITHMS
xf
In computing, we focus on the type of problems categorically known as algorithmic problems, where their
O
solutions are expressible in the form of algorithms. The term ‘algorithm’ was derived from the name of
Mohammed al-Khwarizmi, a Persian mathematician in the nineth century (Al-Khwarizmi → Algorism
(in Latin) → Algorithm). The typical meaning of an algorithm is a formally defined procedure for performing
some calculation. If a procedure is formally defined, then it must be implemented using some formal language,
and such languages are known as programming languages. The algorithm gives the logic of the program, that
is, a step-by-step description of how to arrive at a solution.
In general terms, an algorithm provides a blueprint to writing a program to solve a particular problem. It
is considered to be an effective procedure for solving a problem in a finite number of steps. That is, a well-
defined algorithm always provides an answer, and is guaranteed to terminate.
Algorithms are mainly used to achieve software reuse. Once we have an idea or a blueprint of a solution,
we can implement it in any language, such as C, C++, Java, and so on. In order to qualify as an algorithm, a
sequence of instructions must possess the following characteristics:
• Precision: The instructions should be written in a precise manner.
• Uniqueness: The outputs of each step should be unambiguous, i.e., they should be unique and only depend
on the input and the output of the preceding steps.
ss
processing, and then the result of the processing is written to an output device.
re
The data is stored in the computer’s memory in the form of variables or constants. The state of an algorithm
is defined as its condition regarding current values or contents of the stored data.
yP
An algorithm is a list of precise steps and the order of steps determines the functioning of the algorithm.
The flow of control (or the control flow) of an algorithm can be specified as top-down or bottom-up
sit
approach. Thus, the flow of control specifies the order in which individual instructions of an algorithm are
executed.
er
Algorithms are used to manipulate the data for a given problem. For a complex problem, its algorithm is
Un
often divided into smaller units called functions (or modules). This process of dividing an algorithm into
modules/functions is called modularization. The key advantages of functions (or modularization) are as
follows:
d
• Each function can be designed independently. While designing one function, the details of other functions
can be ignored, thereby enhancing clarity in design which in turn simplifies implementation, debugging,
xf
There are two main approaches to design an algorithm—top-down approach and bottom-up approach, as
shown in Figure 1.1.
Top-down approach A top-down design approach starts by dividing the complex algorithm into one or
more functions. These functions can further be decomposed into one or more sub-functions, and this process
of decomposition is iterated until the desired level of module complexity is achieved. Top-down design
method is a form of stepwise refinement where we begin with the topmost module and incrementally add
functions that it calls.
Therefore, in a top-down approach, we start from an abstract design and then at each step, this design is
refined into more concrete levels until a level is reached that requires no further refinement.
Bottom-up approach A bottom-up approach is just the reverse of top-down approach. In the bottom-up
design, we start with designing the most basic or concrete functions and then proceed towards designing
higher level functions. The higher level functions are implemented by using the operations performed by
lower level functions. Thus, in this approach sub-functions are grouped together to form a higher level
function. All the higher level functions are clubbed together to form even higher level functions. This process
is repeated until the design of the complete algorithm is obtained.
Top-down vs bottom-up approach Whether the top-down strategy should be followed or a bottom-up
is a question that can be answered depending on the application at hand. While top-down approach follows a
stepwise refinement by decomposing the algorithm into manageable function, the bottom-up approach on the
ss
other hand defines a function and then groups together several functions to form a new higher level function.
Top-down approach is highly appreciated for ease in documenting the functions, generation of test
re
cases, implementation of code, and debugging. However, it is also criticized because the sub-functions are
yP
analysed in isolation without concentrating on their communication with other functions or on reusability of
components and little attention is paid to data, thereby ignoring the concept of information hiding.
The bottom-up approach allows information hiding as it first identifies what has to be encapsulated within a
sit
function and then provides an abstract interface to define the function’s boundaries as seen from the clients. But all
this is difficult to be done in a strict bottom-up strategy. Some top-down activities need to be performed for this.
er
All in all, design of complex algorithms must not be constrained to proceed according to a fixed pattern
iv
is laid on writing a good and effective algorithm and this emphasis makes computer science distinct from
or
other disciplines. For example, computer science is distinct from theoretical mathematics because those
practitioners are typically satisfied with just proving the existence of a solution to a problem but in computer
xf
science, the problem is not solved until the algorithm is used to implement the solution.
O
We will now discuss about the sequence of steps one must typically follow for designing an effective algorithm.
1. Understanding the problem
2. Determining the capabilities of the computational device
3. Exact/approximate solution
4. Select the appropriate data structure
5. Algorithm design techniques
6. Methods of specifying an algorithm
7. Proving an algorithms correctness
8. Analysing the performance of an algorithm
Understanding the problem The problem given should be clearly and completely understood. It is
compared with earlier problems that have already been solved to check if it is similar to them and a known
algorithm exists. If the algorithm is available, it is used otherwise a new one has to be developed.
Determining the capabilities of the computational device After understanding the problem, the
capabilities of the computing device should be known. For this, the type of the architecture, speed and
memory availability of the device are noted.
Exact/approximate solution The next step is to develop the algorithm. The algorithm must compute
correct output for all possible and legitimate inputs. This solution can be an exact solution or an approximate
solution. For example, you can only have an approximate solution in case of finding square root of number
or finding the solutions of nonlinear equations.
Select the appropriate data structure A data type is a well-defined collection of data with a well-
defined set of operations on it. A data structure is basically a group of data elements that are put together
under one name, and which defines a particular way of storing and organizing data in a computer so that it
can be used efficiently. The elementary data structures are as follows.
• List: Allows fast access of data.
• Sets: Treats data as elements of a set. Allows application of operations such as intersection, union, and
equivalence.
• Dictionaries: Allows data to be stored as a key-value pair.
ss
Algorithm design techniques Developing an algorithm is an art which may never be fully automated.
By mastering the design techniques, it will become easier for you to develop new and useful algorithms.
re
Examples of algorithm design techniques include dynamic programming.
yP
Methods of specifying an algorithm An algorithm is just a sequence of steps or instructions that can
be used to implement a solution. After writing the algorithm, it is specified either using a natural language or
with the help of pseudocode and flowcharts. We will read about them in the next section.
sit
Proving algorithms correctness Writing an algorithm is not just enough. You need to prove that it
er
computes solutions for all the possible valid inputs. This process is often referred to as algorithm validation.
Algorithm validation ensures that the algorithm will work correctly irrespective of the programming language
iv
required to execute that algorithm. This is a challenging task and is often used to compare different algorithms
or
for a particular problem. The result of the comparison helps us to choose the best solution from all possible
solutions. Analysis of the algorithm also helps us to determine whether the algorithm will be able to meet any
xf
Sequence Sequence means that each step of the algorithm is executed in the specified order. An algorithm
to add two numbers is given as follows. This algorithm performs the steps in a purely sequential order.
Step 1 : Start
Step 2 : Input first number as A
Step 3 : Input second number as B
Step 4 : Set Sum = A + B
Step 5 : Print Sum
Step 6 : End
ss
Decision Decision statements are used when the outcome of the process depends on some condition. For
example, if x = y, then print “EQUAL”. Hence, the general form of the if construct can be given as follows:
re
IF condition then process
yP
A condition in this context is any statement that may evaluate either to a true value or a false value. In the
preceding example, the variable x can either be equal or not equal to y. However, it cannot be both true and
sit
false. If the condition is true then the process is executed.
A decision statement can also be stated in the following manner:
er
IF condition
iv
then process1
Un
ELSE process2
This form is commonly known as the if-else construct. Here, if the condition is true then process1 is
d
executed, else process2 is executed. An algorithm to check the equality of two numbers is shown below.
or
Step 1 : Start
Step 2 : Input first number as A
Step 3 : Input second number as B
Step 4 : IF A = B
Print "Equal"
ELSE
Print "Not equal" [END of IF]
Step 5 : End
Let us look at the following two simple algorithms to find the greatest among three numbers.
Step 1: Start
Step 2: Read the three numbers A,B,C
Example 1.4 Algorithm to find the greatest of three numbers using an additional variable MAX
Step 1:
Start
Step 2:
Read the three numbers A,B,C
ss
Step 3:
Compare A and B. If A is greater, store Ain MAX, else store B in MAX
Step 4:
C
ompare MAX and C. If MAX is greater, output "MAX is greater" else output
re
"C is greater"
Step 5: End
yP
sit
Both the algorithms given in Examples 1.3 and 1.4 accomplish same goal, but in different ways. The
programmer selects the algorithm based on the advantages and disadvantages of each algorithm. For example,
er
the first algorithm has more number of comparisons, whereas in the second algorithm an additional variable
MAX is used to do the comparison.
iv
Iteration or repetition which involves executing one or more steps for a number of times, can be
Un
implemented using constructs such as the while loops and for loops. These loops execute one or more steps
until some condition is true.
d
Step 1: Start
Step 2: [initialize] Set I = 1, N = 10
O
Example 1.6 Design an algorithm for adding the test scores given as: 26, 49, 98, 87, 62, 75.
Step 1: Start
Step 2: sum = 0
Step 3: Get a value
Step 4: sum = sum + value
Step 5: If next value is present, go to step 3. Otherwise, go to step 6
Step 6: Print the sum
Step 7: End
Examples 1.5 and 1.6 demonstrate the application of repetition and iteration logic in an algorithm.
Some more examples to depict the concept of control structures in algorithms are given as follows.
Step 1: Start
Step 2: Input first number as A
Step 3: Input second number as B
Step 4: Set temp = A
Step 5: Set A = B
Step 6: Set B = temp
Step 7: Print A, B
Step 8: End
ss
re
Example 1.8 Write an algorithm to find the larger of two numbers.
yP
Step 1:
Start
Step 2:
Input first number as A
sit
Step 3:
Input second number as B
Step 4:
IF A > B
er
Print A
ELSE IF A < B
iv
Print B
Un
ELSE
Print "The numbers are equal"
[END OF IF]
d
Step 5: End
or
xf
Step 1: Start
Step 2: Input number as A
Step 3: IF A % 2 = 0
Print "Even"
ELSE
Print "Odd"
[END OF IF]
Step 4: End
Example 1.10 Write an algorithm to print the grade obtained by a student using the following rules:
Marks Grade
Above 75 O
60-75 A
Marks Grade
50-60 B
40-50 C
Less than 40 D
Step 1: Start
Step 2: Enter the marks obtained as M
Step 3: IF M > 75
Print "O"
Step 3: IF M >= 60 and M < 75
Print "A"
ss
Step 4: IF M >= 50 and M < 60
Print "B"
re
Step 5: IF M >= 40 and M < 50
yP
Print "C"
ELSE
Print "D"
sit
[END OF IF]
Step 6: End
er
iv
Example 1.11 Write an algorithm to find the sum of first N natural numbers.
Un
Step 1: Start
d
Step 2: Input N
or
Step 6: Set I = I + 1
[END OF LOOP]
Step 7: Print sum
Step 8: End
Recursion It is a technique of solving a problem by breaking it down into smaller and smaller sub-problems
until you get to a small enough problem that it can be easily solved. Usually, recursion involves a function
calling itself until a specified condition is met. Since a recursive function repeatedly calls itself, it makes use
of the system stack to temporarily store the return address and local variables of the calling function. Every
recursive solution has two major cases. They are:
• Base case, in which the problem is simple enough to be solved directly without making any further calls
to the same function.
• Recursive case, in which first the problem at hand is divided into simpler sub-parts. Second the function
calls itself but with sub-parts of the problem obtained in the first step. Third, the result is obtained by com-
bining the solutions of simpler sub-parts.
Therefore, recursion is defining large and complex problems in terms of smaller and more easily solvable
problems. In recursive functions, a complex problem is defined in terms of simpler problems and the simplest
problem is given explicitly.
(For a detailed study on Recursion and Iteration, refer to Chapter 5)
Step 1: Start
Step 2: Input number as n
Step 3: Call factorial(n)
Step 4: End
ss
factorial(n)
Step 1: Set f = 1
re
Step 2: IF n==1 then return 1
ELSE
yP
Set f=n*factorial(n-1)
Step 3: Print f
sit
er
• A conditional or decision symbol is represented using a diamond. It is basically used to depict a Yes/No
question or a True/False test. The two symbols coming out of it, one from the bottom point and the other
from the right point, corresponds to Yes or True, and No or False, respectively. The arrows should always
be labelled. A decision symbol in a flowchart can have more than two arrows, which indicates that a
complex decision is being taken.
• Labelled connectors are represented by an identifying label inside a circle and are used in complex or
multi-sheet diagrams to substitute for arrows. For each label, the ‘outflow’ connector must have one or
more ‘inflow’ connectors. A pair of identically labelled connectors is used to indicate a continued flow
when the use of lines becomes confusing.
• A pre-defined process symbol is a marker for another process step or series of process flow steps that are
formally defined elsewhere. This shape commonly depicts sub-processes (or subroutines in programming
flowcharts).
Significance of Flowcharts
ss
A flowchart is a diagrammatic representation that illustrates the sequence of steps that must be performed
re
to solve a problem. It is usually drawn in the early stages of formulating computer solutions. It facilitates
communication between programmers and users. Once a flowchart is drawn, programmers can make users
yP
understand the solution easily and clearly.
Flowcharts are very important in the programming of a problem as they help the programmers to
sit
understand the logic of complicated and lengthy problems. Once a flowchart is drawn, it becomes easy for the
programmers to write the program in any high-level language. Hence, the flowchart has become a necessity
er
for better documentation of complex programs.
A flowchart follows the top-down approach in solving problems. Some examples are given as follows.
iv
Un
Example 1.13 D
raw a flowchart to calculate the Example 1.14 D
raw a flowchart to add two
sum of the first 10 natural numbers. numbers.
d
or
START START
xf
NO
Is I = 10?
Print SUM
YES
Display SUM
STOP
STOP
Example 1.15 D
raw a flowchart to Example 1.16 D
raw a flowchart to determine the largest of
calculate the salary of three numbers.
a daily wager.
START
START
Read the
SALARY Input the values of
no_of_hrs, pay_per_hr, A, B, and C
and travel_allowance Print B
YES
Calculate SALARY=(no_of_hr x NO NO
ss
pay_per_hr) + travel_allowance Is A > B? Is B > C? Print C
YES
re
NO
yP
Print SALARY Is A > C? Print C
YES
sit
Print A
STOP
er
STOP
iv
Un
Advantages
• They are very good communication tools to explain the logic of a system to all concerned. They help to
analyse the problem in a more effective manner.
d
• They are also used for program documentation. They are even more helpful in the case of complex
or
programs.
• They act as a guide or blueprint for the programmers to code the solution in any programming language.
xf
They direct the programmers to go from the starting point of the program to the ending point without
O
Limitations
• Drawing flowcharts is a laborious and a time-consuming activity. Just imagine the effort required to draw
a flowchart of a program having 50,000 statements in it!
• Many a times, the flowchart of a complex program becomes complex and clumsy.
• At times, a little bit of alteration in the solution may require complete redrawing of the flowchart.
• The essentials of what is done may get lost in the technical details of how it is done.
• There are no well-defined standards that limit the details that must be incorporated into a flowchart.
1.5.3 Pseudocodes
Pseudocode is a compact and informal high-level description of an algorithm that uses the structural
conventions of a programming language. It facilitates designers to focus on the logic of the algorithm without
getting bogged down by the details of language syntax. An ideal pseudocode must be complete, describing
the entire logic of the algorithm, so that it can be translated straightaway into a programming language.
It is basically meant for human reading rather than machine reading, so it omits the details that are not
essential for humans. Such details include variable declarations, system-specific code, and subroutines.
Pseudocodes are an outline of a program that can easily be converted into programming statements. They
consist of short English phrases that explain specific tasks within a program’s algorithm. They should not
include keywords in any specific computer language.
The sole purpose of pseudocodes is to enhance human understandability of the solution. They are commonly
used in textbooks and scientific publications for documenting algorithms, and for sketching out the program
structure before the actual coding is done. This helps even non-programmers to understand the logic of the designed
solution. There are no standards defined for writing a pseudocode, because a pseudocode is not an executable
program. Flowcharts can be considered as graphical alternatives to pseudocodes, but require more space on paper.
Example 1.17 W
rite a pseudocode for calculating the price of a product after adding the sales tax to
its original price.
ss
1. Start
re
2. Read the price of the product
3. Read the sales tax rate
yP
4. Calculate sales tax = price of the item x * sales tax rate
5. Calculate total price = price of the product + sales tax
sit
6. Print total price
7. End
er
Variables: price of the item, sales tax rate, sales tax, total price
iv
Un
Example 1.18 W
rite a pseudocode to calculate the weekly wages of an employee. The pay depends
on wages per hour and the number of hours worked. Moreover, if the employee has
d
worked for more than 30 hours, then he or she gets twice the wages per hour, for every
or
1. Start
2. Read hours worked
O
Example 1.19 W
rite a pseudocode to read the marks of 10 students. If marks is greater than 50, the
student passes, else the student fails. Count the number of students passing and failing.
1. Start
2. Set pass to 0
3. Set fail to 0
4. Set no of students to 1
5. WHILE no of students < 10
a. input the marks
b. IF marks >= 50 then
Set pass = pass + 1
ELSE
Set fail = fail + 1
ENDIF
ENDWHILE
6. Display pass
7. Display fail
ss
8. End
Variables: pass, fail, no of students, marks
re
yP
1.5.4 Programming Languages
A programming language is a language specifically designed to express computations that can be performed
sit
by a computer. Programming languages are used to create programs that control the behaviour of a system,
to express algorithms, or as a mode of human communication.
er
Usually, programming languages have a vocabulary of syntax and semantics for instructing a computer
to perform specific tasks. The term programming language refers to high-level languages such as BASIC
iv
(Beginners’ All-purpose Symbolic Instruction Code), C, C++, COBOL (Common Business Oriented Language),
Un
FORTRAN (Formula Translator), Python, Ada, and Pascal, to name a few. Each of these languages has a unique
set of keywords (words that it understands) and a special syntax for organizing program instructions.
Though high-level programming languages are easy for humans to read and understand, the computer can
d
understand only machine language, which consists of only numbers. Each type of central processing unit
or
assembly language. Assembly languages are similar to machine languages, but they are much easier to
program because they allow a programmer to substitute names for numbers.
O
However, irrespective of the language that a programmer uses, a program written using any programming
language has to be converted into machine language so that the computer can understand it. There are two
ways to do this: compile the program or interpret the program.
When planning a software solution, the software development team often faces a common question—
which programming language to use? Many programming languages are available today and each one has
its own strengths and weaknesses. Python can be used to write an efficient code, whereas a code in BASIC is
easy to write and understand; some languages are compiled, whereas others are interpreted; some languages
are well known to the programmers, whereas others are completely new. Selecting the perfect language for a
particular application at hand is a daunting task.
The selection of language for writing a program depends on the following factors:
• The type of computer hardware and software on which the program is to be executed.
• The type of program.
• The expertise and availability of the programmers.
• Features to write the application.
• The built-in features that support the development of software that are reliable and less prone to crash.
• Lower development and maintenance costs.
• Stability and capability to support even more than the expected simultaneous users.
• Elasticity of a language that implies the ease with which new features (or functions) can be added to the
existing program.
• Portability.
• Better speed of development that includes the time it takes to write a code, time taken to find a solution to
the problem at hand, time taken to find the bugs, availability of development tools, experience and skill of
the programmers, and testing regime.
For example, FORTRAN is a particularly good language for processing numerical data, but it does
not lend itself very well to organizing large programs. Pascal can be used for writing well-structured and
readable programs, but it is not as flexible as the C programming language. C++ goes one step ahead of C by
incorporating powerful object oriented features, but it is complex and difficult to learn. Python, however is a
good mix of the best features of all these languages.
1.6 ILLUSTRATIVE PROBLEMS
ss
In this section, we will look into some common problems in computer science and will specify its solution by
writing an algorithm and pseudocode, and drawing its corresponding flowchart. (Besides these, we will study
re
some more illustrative examples in Appendix A.)
yP
1.6.1 Find Minimum in a List
Consider the following requirement specification.
sit
You are given a list of numbers from which you are supposed to find the minimum value. An algorithm is
required for entering the numbers in the list and then calculate the minimum value. The count of numbers to
er
be entered in the list should also be asked from the user.
Before writing the algorithm, just visualize how it works. Take the first number in the list and call it
iv
minimum. Compare the minimum’s value with all other values in the list one by one. The moment you find
a smaller element than the minimum, call it the minimum. Figure 1.3 given below illustrates this concept.
Un
3 5 9 1 4 7 2 6
d
Let MIN = 3, Compare MIN with every element in the list one by one.
or
3 5 9 1 4 7 2 6
xf
3 5 9 1 4 7 2 6
MIN < 9, so no change
3 5 9 1 4 7 2 6
MIN < 1, so set MIN = 1
3 5 9 1 4 7 2 6
MIN < 4, so no change
3 5 9 1 4 7 2 6
MIN < 7, so no change
3 5 9 1 4 7 2 6
MIN < 2, so no change
3 5 9 1 4 7 2 6
MIN < 6, so no change
Figure 1.3 Finding minimum value in a list
The step-wise approach for solving the problem of finding the minimum in a list is demonstrated through
Algorithm 1.1, Flowchart 1.1, and Pseudocode 1.1.
Algorithm 1.1
Step 1: Start
Step 2: READ the count of numbers as N
Step 3: SET I = 0
Step 4: READ the first element as MIN
Step 5: REPEAT Steps 6-8 WHILE I < N – 1
Step 6: READ the next number as NUM
Step 7: IF MIN < NUM
SET MIN = NUM
ss
Step 8: SET I = I + 1
Step 9: PRINT MIN
re
Step 10: End
yP
Flowchart 1.1 sit
Start
er
of numbers as N
Un
SET I = 0
d
or
element as MIN
O
NO
Is I < N - 1? Print MIN
YES
NO
Is MIN < NUM?
YES
SET I = I + 1
Pseudocode 1.1
ss
1.6.2 Insert a Card in a List of Sorted Cards
re
Inserting a card in a list of sorted cards is same as inserting an element into a sorted list of numbers. For this,
yP
start from the end of the list and compare the new element with the elements of the list to find a suitable
position at which the new element has to be inserted. While comparing, also shift the elements one step ahead
to create a vacancy for the new element. Figure 1.4 given below illustrates this concept.
sit
Position 0 1 2 3 4 5 Element To Be Inserted
er
Original List 4 6 9 10 11 7
iv
7>11 × 4 6 9 10 11
Un
7>10 × 4 6 9 10 11
7>9 × 4 6 9 10 11
d
7>6 √ 4 6 7 9 10 11
or
The step-wise approach for solving the problem of inserting a card in a list of sorted cards is represented
through Algorithm 1.2, Flowchart 1.2, and Pseudocode 1.2.
O
Algorithm 1.2
Step 1: Start
Step 2: READ Number of elements in the sorted list as N
Step 3: SET I=0
Step 4: REPEAT Steps 5 and 6 WHILE I < N
Step 5: READ the Sorted list element as List[I]
Step 6: SET I = I + 1
Step 7: READ Element to be inserted as X
Step 8: SET I = N-1
Step 9: REPEAT Step 10 and 11 WHILE I >= 0 AND X<List[I]
Step 10: List[I+1] = List[I]
Step 11: SET I = I - 1
Step 12: List[I+1] = X
Step 13: End
Flowchart 1.2
Start
Read Number of
elements in the
sorted list as
SET I = 0
ss
NO Read Element to
Is I < N?
be insert as X
re
YES
yP
SET I = I + 1 Read the sorted list SET I = N - 1
element as List[I]
sit
er
Is I > 0 AND NO
SET List[I] = X
X<List[I]?
iv
Un
Stop
SET List[I+1] = List[I]
d
SET I = I - 1
or
xf
O
Pseudocode 1.2
Start
Read Number of elements in the sorted list as N
Set I=0
WHILE I < N
Read the Sorted list element as List[I]
Set I = I + 1
Read element to be inserted as X
Set I = N-1
WHILE I >= 0 AND X<List[I]
List[I+1] = List[I]
Set I = I - 1
List[I+1] = X
End
ss
too high, or correct, it is better to start by guessing N/2. If the number selected by the computer is less than
N/2, then using the computer’s information that the guess is too high, you can eliminate all the numbers from
re
N/2 to N in just one go. If the number selected by the computer is greater than N/2, then all elements from
yP
1 through N/2 are eliminated right away. So with one guess you have narrowed down your possible guesses
by half. Isn’t that interesting and an intelligent move? Keep on cutting down the set of possible numbers by
half with every guess that you make.
sit
While linear search technique required N guesses to win the game, binary search technique, on the other
hand, can make you win (or find the number) in at most log2N+1 guesses. The following table shows the
er
maximum number of guesses for linear search and binary search for a few number sizes:
iv
10 10 4
100 100 7
d
1,000 1,000 10
or
10,000 10,000 14
xf
100,000 100,000 17
1,000,000 1,000,000 20
O
The step-wise approach for solving the problem of guessing an integer number in a given range is
demonstrated through Algorithm 1.3, Flowchart 1.3, and Pseudocode 1.3.
Algorithm 1.3
Step 1: Start
Step 2: SET I = 0
Step 3: READ the range of numbers as N
Step 4: SET NUM as a randomly selected number from 1 to N
Step 5: READ VAL as a value guessed by the user
Step 6: SET I = I + 1
Step 7: IF VAL = NUM
THEN PRINT "YOU WIN... You guessed the number in Ith Turn"
Go to Step 10
Flowchart 1.3
ss
re
Start
yP
SET I = 0
sit
Read the range
er
of numbers as N
iv
Un
SET I = 1 +1
O
PRINT "VALUE
TOO LOW... Is VAL > NUM?
PLAY AGAIN...."
PRINT "VALUE
TOO HIGH...
PLAY AGAIN...."
Pseudocode 1.3
Start
Set I = 0
Read the range of numbers as N
Set NUM as a randomly selected number from 1 to N
Read VAL as a value guessed by the user
Set I = I + 1
While VAL != NUM
IF VAL = NUM
THEN PRINT "YOU WIN... You guessed the number in Ith Turn"
Exit
ELSEIF VAL > NUM
ss
THEN PRINT "VALUE TOO HIGH… PLAY AGAIN…."
ELSE
re
THEN PRINT "VALUE TOO LOW… PLAY AGAIN…."
End
yP
sit
1.6.4 Tower of Hanoi
The tower of Hanoi is one of the main applications of recursion. It says, ‘if you can solve n–1 cases, then you
er
We will discuss the tower of Hanoi problem using one, then two, and finally three rings. Figures 1.5(a) and
(b) explain the working of the tower of Hanoi problem using one and two rings.
Un
d
or
A B C A B C A B C
(Step 1) (Step 1) (Step 2)
xf
O
A B C A B C A B C
(Step 2) (Step 3) (Step 4)
(If there is only one ring, (If there is two rings, then first move ring 1 to the spare
then simply move the ring pole and then move ring 2 from source to the destination.
from source to the destination.) Finally move ring 1 from spare to the destination.)
(a) (b)
Figure 1.5 Working of tower of Hanoi problem using one and two rings
Now, consider at Figure 1.6 which shows three rings mounted on pole A. The problem is to move all these
rings from pole A to pole C while maintaining the same order. The main issue is that the smaller disk must
always come above the larger disk.
3 Disks
(1)
A B C A B C
(2) (3) (4)
A B C A B C A B C
(5) (6) (7)
A B C A B C A B C
Figure 1.6 Solving the Tower of Hanoi problem
ss
We will be solving this using a spare pole. In our case, A is the source pole, C is the destination pole, and B
re
is the spare pole. To transfer all the three rings from A to C, we will first shift the upper two rings (n–1 rings)
from the source pole to the spare pole (refer to Steps 1, 2 and 3 of Figure 1.6). Now that n–1 rings have been
yP
removed from pole A, the nth ring can be easily moved from the source pole (A) to the destination pole (C)
(refer to Step 4 of Figure 1.6). The final step is to move the n–1 rings from the spare pole (B) as well as pole
sit
(A) to the destination pole (C) (refer to Steps 5, 6, and 7 of Figure 1.6).
To summarize, the solution to our problem of moving n rings from A to C using B as spare can be given as:
er
Recursive case:
Un
Step 3 − Move n-1 disks from the spare pole to the destination pole
The step-wise approach for solving the problem of tower of Hanoi is demonstrated through Algorithm 1.4,
O
Step 1: Begin
Step 2: IF disk = 1
THEN Go to step 3
ELSE
Go to step 4
Step 3: Move disk from source to dest and then Go to Step 7
Step 4: CALL Hanoi(disk-1, source, spare, dest)
Step 5: Move disk from source to dest
Step 6: CALL Hanoi(disk-1, spare, dest, source)
Step 7: End
Flowchart 1.4
Is disk==1?
Hanoi (disk-1, source, Move disk from
spare, dest) source to dest
Hanoi (disk-1,
spare, dest, source)
ss
re
End Hanoi
yP
Pseudocode 1.4 sit
Begin Procedure Hanoi(disk, source, dest, spare)
IF disk = 1
er
ELSE
CALL Hanoi(disk -1, source, spare, dest)
Un
Note: Refer to Program 5.17 for the code demonstrating the implementation of the solution of the
xf
Types of Errors
While writing programs, very often we get errors Types of errors
in our programs. These errors if not removed will
either give erroneous output or will not let the
compiler to compile the program. These errors
are broadly classified under four groups as shown Run-time Syntax Linker Logical
in Figure 1.7. errors errors errors errors
Run-time Errors As the name suggests, run-
Figure 1.7 Types of errors
time errors occur when the program is being run
executed. Such errors occur when the program performs some illegal operations like
• dividing a number by zero
• opening a file that already exists
• lack of free memory space
• finding square or logarithm of negative numbers
Run-time errors may terminate program execution, so the code must be written in such a way that it handles
all sorts of unexpected errors rather terminating it unexpectedly.
Syntax Errors Syntax errors (also known as compile-time errors) are generated when rules of a programming
language are violated. Python interprets (executes) each instruction in the program line by line. The moment the
interpreter encounters a syntactic error, it stops further execution of the program.
Semantic or Logical Errors Semantic errors are those errors which may comply with rules of the programming
language but gives an unexpected and undesirable output which is obviously not correct. For example, if you write a
program to add two numbers but instead of writing ‘+’ symbol, you put the ‘–’ symbol.Then Python will subtract
the numbers and returns the result. But, actually the output is different from what you expected.
Logical errors are errors in the program code. Such errors are not detected by the compiler, and programmers
must check their code line by line or use a debugger to locate and rectify the errors. Logical errors occur due to
incorrect statements.
Linker Errors These errors occur when the linker is not able to find the function definition for a given prototype.
ss
re
yP
Summary
• Programming means writing computer programs. While • An algorithm is analysed to measure its performance in
sit
programming, the programmers takes an algorithm and terms of CPU time and memory space required to exe-
code the instructions in a particular programming lan- cute that algorithm
er
guage, so that it can be executed by a computer. • Sequence means that each step of the algorithm is exe-
• An algorithm provides a blueprint to writing a program cuted in the specified order.
iv
to solve a particular problem. • Decision statements are used when the outcome of the
Un
• In the course of processing, data is read from an input process depends on some condition.
device, stored in computer’s memory for further pro- • Iteration or Repetition involves executing one or more
cessing and then the result of the processing is written steps for a number of times, can be implemented using
d
to an output device. constructs such as the while loops and for loops.
or
• The data is stored in the computer’s memory in the form • Programming languages have a vocabulary of syntax
of variables or constants. and semantics for instructing a computer to perform
xf
• The flow of control (or the control flow) of an algorithm specific tasks.
can be specified as top-down or bottom-up approach. • Pseudocode facilitates designers to focus on the logic
O
• For a complex problem, its algorithm is often divided of the algorithm without getting bogged down by the
into smaller units called functions (or modules). details of language syntax.
• Algorithm validation ensures that the algorithm will
work correctly irrespective of the programming lan-
guage in which it will be implemented.
Glossary
Program A set of instructions that tells the computer how Top-down design approach Algorithm design approach
to solve a particular problem. that starts by dividing the complex algorithm into one or
Algorithm A step by step instructions that tells the more functions.
computer how to solve a particular problem. Bottom-up design In this approach, we start with
Programming The act of writing programs. designing the most basic or concrete functions and then
Instruction A single operation which when executed proceed towards designing higher level functions.
convert one state to other. Programming language A language specifically
Modularization The process of dividing an algorithm designed to express computations that can be performed
into modules/functions. by a computer.
Exercises
Fill in the blanks
1. A ________is a set of instructions that tells the 9. The ______ symbol is always the first and the last
computer how to solve a particular problem. symbol in a flowchart.
2. Algorithms are mainly used to achieve _________. 10. ______ is a form of structured English that describes
ss
3. _____ and _______ statements are used to change algorithms.
the sequence of execution of instructions. 11. ______ is used to express algorithms and as a mode
re
4. ______ is a formally defined procedure for of human communication.
performing some calculation. 12. The process of dividing an algorithm into modules/
yP
5. ______ statements are used when the outcome of the functions is called _________.
process depends on some condition. 13. In a _________ approach, we start from an abstract
sit
6. Repetition can be implemented using constructs such design and then at each step, this design is refined
as ______, ______, and ______. into more concrete levels until a level is reached that
7. A complex algorithm is often divided into smaller requires no further refinement.
er
8. _____ design approach starts by dividing the complex breaking it down into smaller and smaller sub-
algorithm into one or more modules. problems until you get to a small enough problem
Un
1. An algorithm solves a problem in a finite number of 6. Terminal symbol depicts the flow of control of the
steps. program.
xf
2. Flowcharts are drawn in the early stages of 7. Labelled connectors are square in shape.
formulating computer solutions. 8. The outputs of each step of an algorithm should be
O
3. The main focus of pseudocodes is on the details of unambiguous. This means that is should be precise.
the language syntax. 9. You can have maximum one function in a algorithm.
4. Algorithms are implemented using a programming 10. A top-down design approach starts by dividing the
language. complex algorithm into one or more functions.
5. Repetition means that each step of the algorithm is 11. Pseudocode is written using the syntax of a particular
executed in a specified order. programming language.
5. Which of the following details are omitted in (b) measure the memory consumed
pseudocodes? (c) check if it is correct
(a) variable declaration (d) all of these
(b) system specific code 8. Programming languages have a vocabulary of
(c) subroutines ___________ for instructing a computer to perform
(d) all of these specific tasks.
6. A single operation which when executed convert one (a) syntax (b) semantics
state to other is called _________. (c) both of these (d) none of these
(a) instruction (b) program 9. Syntax and semantics of a language are strictly
(c) software (d) control checked in ___________.
7. Algorithm is validated to (a) algorithm (b) flowchart
(a) measure its CPU time (c) pseudocode (d) program
Review Questions
ss
1. Define an algorithm. How is it useful in the context 11. Write an algorithm and draw a flowchart that
of software development? calculates salary of an employee. Prompt the user
re
2. Explain and compare the approaches for designing to enter the Basic Salary, HRA, TA, and DA. Add
yP
an algorithm. these components to calculate the Gross Salary. Also
3. What is modularization? deduct 10% salary from the Gross Salary to be paid
4. Explain sequence, repetition, and decision as tax.
sit
statements. Also give the keywords used in each type 12. Draw a flowchart and write an algorithm and a
of statement. psuedocode for the following problem statements
er
5. With the help of an example, explain the use of a (a) Cook maggi
flowchart. (b) Cross road
iv
6. How is a flowchart different from an algorithm? (c) Calculate bill of items purchased
Do we need to have both of them for program (d) To find out whether a number is positive or
Un
development? negative
7. What do you understand by the term pseudocode? (e) Print “Hello” five times on the screen
8. Differentiate between algorithm and pseudocodes. (f) Find area of a rectangle
d
10. What do you understand by the term recursion? (h) Find the sum of first 10 numbers
xf
O
Answers
Fill in the Blanks
1. Program 5. Decision 8. top-down 12. Modularization
2. software reuse 6. while, do-while, and for 9. Terminal symbols 13. top-down
3. Decision, repetition loops 10. Psuedocode 14. Recursion
4. Algorithm 7. functions or modules 11. Flowcharts