Вы находитесь на странице: 1из 228

SYLLABUS

(Regulation 2017) Anna University

GE8151 – PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT I – ALGORITHMIC PROBLEM SOLVING


Algorithms, building blocks of algorithms (statements, state, control flow, functions),
notation (pseudo code, flow chart, programming language), algorithmic problem solving, simple
strategies for developing algorithms (iteration, recursion). Illustrative problems: find minimum in
a list, insert a card in a list of sorted cards, guess an integer number in a range, Towers of Hanoi.

UNIT II – DATA, EXPRESSIONS, STATEMENTS


Python interpreter and interactive mode; values and types: int, float, boolean, string, and
list; variables, expressions, statements, tuple assignment, precedence of operators, comments;
modules and functions, function definition and use, flow of execution, parameters and arguments;
Illustrative programs: exchange the values of two variables, circulate the values of n variables,
distance between two points.

UNIT III – CONTROL FLOW, FUNCTIONS


Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
conditional (if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful functions: return
values, parameters, local and global scope, function composition, recursion; Strings: string slices,
immutability, string functions and methods, string module; Lists as arrays. Illustrative programs:
square root, gcd, exponentiation, sum an array of numbers, linear search, binary search.

UNIT IV – LISTS, TUPLES, DICTIONARIES


Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and methods;
advanced list processing – list comprehension; Illustrative programs: selection sort, insertion sort,
mergesort, histogram.

UNIT V – FILES, MODULES, PACKAGES


Files and ex-ception: text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative programs:
word count, copy file.
TABLE OF CONTENTS

UNIT - 1 ALGORITHMIC PROBLEM SOLVING


1.1 Algorithm 1.1
1.1.1 Characteristics of an Algorithm 1.1
1.1.2 Qualities of an Algorithm 1.2
1.1.3 Representation of Algorithm 1.2
1.2 Basic Building Blocks of Algorithm 1.2
1.2.1 Sequence Structure 1.2
1.2.2 Selection Structure 1.3
1.2.3 Iteration Structure 1.3
1.3 Notations 1.3
1.3.1 Pseudocodes – Introduction 1.3
1.3.2 Basic Guidelines for Writing Pseudocode 1.4
1.3.3 Advantages of Pseudocode 1.5
1.3.4 Disadvantages of Pseudocode 1.5
1.4 Flowchart 1.5
1.4.1 Flowchart Symbols 1.5
1.4.2 Basic Guidelines for Preparing Flowchart 1.6
1.4.3 Advantages of Flowcharts 1.7
1.5 Programming Language 1.8
1.6 Algortithmic Problem Solving 1.9
1.7 Simple Strategies for Developing Algorithms 1.17
1.8 Towers of Hanoi 1.20

UNIT 2 – DATA, EXPRESSIONS, STATEMENTS


2.1 introduction: Python 2.1
2.2 Python interpreter and interactive Mode 2.1
2.3 Values and Types 2.2
2.4 Variable 2.6
2.5 Expressions and Statements 2.7
2.5.1 Assigning Values in Python 2.7
2.5.2 Variable Declaration 2.7
2.5.3 Multiple Assignments 2.8
2.6 Operators 2.8
2.6.1 Types of Operator 2.9
2.6.2 Operator Precedence 2.16
2.7 Comments 2.17
2.8 Modules and Functions 2.17
2.8.1 Modules 2.17
2.8.2 Function Definition and Use 2.17
2.8.3 Defining a Function 2.21
2.8.4 Calling a Function 2.22
2.8.5 Uses of Function 2.23
2.8.6 Advantages of Functions 2.23
2.9 Flow of Execution 2.24
2.10 Parameters and Arguments 2.24
2.10.1 Functions with No Arguments 2.24
2.10.2 Functions with Arguments 2.25
2.10.3 Functions with Return Value 2.25
2.11 Illustrative Programs 2.26
2.11.1 To Exchange the Values of Two Variables 2.26
2.11.2 To Test for Leap Year 2.26
2.11.3 To Test for Leap Year Using Calendar Module 2.27
2.11.4 To Sum All the Numbers in a List 2.27
2.11.5 To Reverse a String 2.27
2.11.6 To Check Whether a Number is in a Given Range 2.28
2.11.7 To Print the Even Numbers From a Given List 2.28
2.11.8 Circulates/Rotates the List Values for Given Number of Times (Order) 2.28
2.7.9 Find the Distance Between Two Points (Xc,Yc) and (Xp,Yp). 2.29
UNIT 3 – CONTROL FLOW
3.1 Conditionals: Boolean Values and Operators 3.1
3.2 Operators 3.1
3.3 Operators Precedence 3.6
3.4 Decision Making 3.7
3.4.1 (i) If Statement 3.7
3.4.2 (ii) If... Else Statement 3.8
3.4.3 (iii) If...Elif…Else Statement 3.9
3.4.4 (iv) Nested Conditionals 3.10
3.5 Iteration 3.12
3.6 Fruitful Functions 3.17
3.7 Scope of the Variable 3.19
3.7.1 Global and Local Variables in Functions 3.20
3.7.2 Nonlocal Variables 3.22
3.8 Composition 3.23
3.9 Recursion 3.25
3.10 Strings 3.26
3.11 String Slices 3.30
3.12 String are Immutable 3.30
3.13 String Functions and Methods 3.31
3.14 String Module 3.33
3.15 Lists as Array 3.34

UNIT 4 – COMPOUND DATA: LISTS, TUPLES, DICTIONARIES


4.1 Lists 4.1
4.1.1 Accessing Elements in Lists Using Subscript Operator 4.1
4.1.2 List Operations 4.2
4.1.3 List Slices 4.2
4.1.4 List Methods 4.3
4.1.5 List Loop 4.7
4.1.6 Mutability 4.8
4.1.7 Aliasing 4.9
4.1.8 Cloning Lists 4.11
4.1.9 List Parameters 4.13
4.1.10 Deleting List Elements 4.14
4.1.11 Python Functions for List Operations 4.15
4.1.12 List Comprehension 4.16
4.2 Tuples 4.18
4.2.1 Advantages of Tuple Over List 4.18
4.2.2 Accessing Values 4.20
4.2.3 Updating Tuples 4.21
4.2.4 Delete Tuple Elements 4.22
4.2.5 Tuple Assignment 4.23
4.2.6 Tuple Methods 4.25
4.2.7 Other Tuple Operations 4.26
4.2.8 Tuples As Return Values 4.26
4.2.9 Built-in Functions with Tuple 4.27
4.2.10 Variable-Length Argument Tuples 4.27
4.2.11 Comparing Tuples 4.28
4.3 Dictionaries 4.30
4.3.1 Built-in Dictionary Functions & Methods 4.32
4.3.2 Access, Update, and Add Elements 4.33
4.3.3 Delete or Remove Elements 4.33
4.3.4 Sorting 4.34
4.3.5 Iterating Through 4.34
4.3.6 Reverse Lookup 4.35
4.3.7 Inverting a Dictionary 4.35
4.3.8 Memoization (Memos) 4.36
4.4 Illustrative Programs 4.38
4.4.1 The Selection Sort Algorithm 4.38
4.4.2 The Insertion Sort Algorithm 4.40
4.4.3 The Merge Sort Algorithm 4.41
4.4.4 The Quick Sort Algorithm 4.42
4.4.5 To Create a Histogram From a Given List of integers. 4.45

Unit – 5 Files, Modules, Packages

5.1 Files 5.1


5.1.1 Reading and Writing 5.1
5.1.2 format Operator 5.6
5.1.3 Command Line Arguments 5.10
5.2. Errors and Exception 5.12
5.2.1 Errors 5.12
5.2.2 Exceptions 5.14
5.2.2.1 User-Defined Exceptions 5.20
5.3 Modules 5.21
5.3.1 Writing Modules 5.23
5.3.2 Locating Modules 5.26
5.4 Packages 5.27
5.4.1 Steps to Create a Python Package 5.27
5.5 Illustrative Programs 5.28
5.5.1 To Handle Exception when File Open Fails 5.28
5.5.2 To Raise an Exception when the User input is Negative 5.29
5.5.3 To Count Number of words in a File 5.29
5.5.4 To Count the Frequency of Words in a Text File 5.29
5.5.5 To Copy a Content of one File to another 5.30
5.6.6 To Append Text to a File and Display the Text 5.31
Appendix -A Lab Programs App-A.1
Appendix -B Two Mark and 16 Mark Questions with Answer App-B.1
Appendix -C Previous Year University Question papers App-C.1
UNIT - 1

ALGORITHMIC PROBLEM SOLVING

1.1 ALGORITHM
Algorithm is defined as a step by step procedure for solving any problem.

An algorithm is a sequence of finite instructions, often used for calculation and data
processing.

A step by step method


Input Output
for solving a problem

Example:
Algorithm for Calculating Area of the Circle
(1) Start
(2) Read the value of radius r
(3) Calculate Area=3.14*r*r
(4) Print the Area of the circle
(5) Stop

Consider the value of radius r=5


Area=3.14*5*5 =78.5

1.1.1 Characteristics of an Algorithm


An algorithm has the following characteristics.

•• Algorithm has a finite number of inputs.


•• Every instruction should be precise and unambiguous.
•• The algorithm should be proper termination.
•• Effectiveness of each step is very important.
•• The desired output must be obtained only after the algorithm terminates.
•• The algorithm should be written in sequence.
1.2 Problem Solving and Python Programming

1.1.2 Qualities of an Algorithm


Different algorithm may perform the same task with different set of instructions. An
algorithm is written in such a way that it optimizes all necessary conditions.

The factors that determine the quality of algorithm are


•• The algorithm should provide accurate result than others.
•• It should require minimum computer memory.
•• The time taken to execute any program is considered as a main quality. Lesser the time
taken better the quality.
•• The procedure of an algorithm must be in a sequential form.

1.1.3 Representation of Algorithm


•• Algorithms can be expressed in any language from natural languages (like English,
French, etc.) to programming languages (like Basic, Fortran, etc.).
•• Algorithm has a starting point and a final point. Between these two points are the
instructions that solve the problem.
•• Algorithms often have steps that repeat or require decisions (such as logic or comparison).

1.2 BASIC BUILDING BLOCKS OF ALGORITHM


Three basic building blocks of algorithm are Sequence, Selection, and Iteration.
Building Block Common name Description
Sequence Action Instructions are executed in sequential order (from
first to last).
Selection Decision or A decision is making a choice among several actions
Branching (condition checking).
Iteration Repetition or Loop A loop is one or more instructions that the computer
performs repeatedly.

1.2.1 Sequence Structure


This is the most common form of control structure. Each statement in the program is executed
one after the other in the given order. The flow of sequence structure is shown in Figure.1.1

Process 1

Process 1

Process n

Figure 1.1. Sequence structure


Algorithmic Problem Solving 1.3

1.2.2 Selection Structure


The selection control structure is the presentation of a condition and the choice between two
actions.The choice made depends on whether the condition is true or false.It is also called a decision
making. The selection structure is shown in figure 1.2.

True If False
A> B

Print A is Big Print B is Big

Figure 1.2. Selection structure.

1.2.3 Iteration Structure


The iterative process is called as repetition or looping.

An iterator is an object that implements next, which is expected to return the next element
of the iterable object that returned it, and raise a Stop Iteration exception when no more elements
are available. The iteration structure is shown in figure 1.3.

True
Condition False
Check

Conditional
code

Figure 1.3. Iteration structure

1.3 NOTATIONS
1.3.1 Pseudocodes – Introduction
Pseudocode is a kind of structural english for designing algorithm. Pseudocodes came from
two words. Pseudo and code "pseudo" means imitation and "code" refer to instructions, written in
a programming language.
1.4 Problem Solving and Python Programming

Pseudocode neither be compiled nor executed, and there are no real formatting or syntax
rules. The benefit of pseudo code is that it enables the programmer to concentrate on the algorithms
without worrying about all the syntactic details of a particular programming language.

Common Keywords used in Pseudocode:


Input: READ, INPUT, OBTAIN, GET Output: PRINT, OUTPUT, DISPLAY,SHOW
Compute: COMPUTE, CALCULATE, DETERMINE
Initialize: SET, INIT
Add one: INCREMENT, BUMP

Example
A pseudocode to add two numbers and display the results:
READ num1, num2
result = num1 + num2
WRITE result

1.3.2 Basic Guidelines for Writing Pseudocode


(a) Write only one Statement per Line
Each statement in your pseudo code should express just one action for the computer. If the
task list is properly drawn, then in most cases each task will correspond to one line of pseudo code.

(b) Capitalize initial keyword


The keywords should be written in capital letters.

In the example above, READ and WRITE are in capital letters. Following are few keywords
we use

IF, ELSE, ENDIF, WHILE, ENDWHILE, REPEAT, UNTIL

(c) Indent to show hierarchy


Indentation is a process of showing the boundaries of the structure.

We will use a particular indentation pattern in each of the design structures:

Sequence : It keeps the statement that are “stacked” in sequence all starting in the same
column.

Selection : It indent the statements that fall inside the selection structure, but not the
keywords that form the selection.

Looping : It indent the statements that fall inside the loop, but not the keywords that form
the loop.
Algorithmic Problem Solving 1.5

(d) End multiline structures


Each structure must end properly, which provides more clarity.

Example
ENDIF for IF statement

(e) Keep statements language independent


Write in whatever language you are most comfortable with. There may be some special
features available in the language that one plan to write the program in. If you are sure it will be
written in that language, then you can use the features.

1.3.3 Advantages of Pseudocode


•• Easily modifiable.
•• No special symbols are used.
•• Implements structured concepts well.
•• No specific syntax is used.
•• It is simple because it uses English-like statements.

1.3.4 Disadvantages of Pseudocode


•• Neighter be compiled nor executed.
•• It’s not visual.

1.4 FLOWCHART
Introduction
A flow chart is a diagrammatic representation, that illustrates the sequence of operations to
be performed to arrive at the solution. Each step in the process is represented by a different symbol
and contains a short description of the process step. The flow chart symbols are linked together with
arrows showing the flow direction of the process.

Flowchart is very helpful in writing programs and explaining them to others. Flowchart
makes us to understand the problem unambiguously. It is often used by the programmer as a program
planning tool for organizing a sequence of steps necessary to solve a problem by a computer.

1.4.1 Flowchart Symbols

Symbol Purpose Description

Terminal(Stop/Start) Represents start and end of flowchart.


1.6 Problem Solving and Python Programming

Symbol Purpose Description

Input/output Represents input and output operation.

Represents arithmetic operations and


Processing
data-manipulations.

Represents the decision making


Decision operation in which there are two
alternatives, true and false.

On-page Connector Used to join different flow line

Indicates the flow of logic by connecting


Flow line
symbols.

1.4.2 Basic Guidelines for Preparing Flowchart


(a) In drawing a proper flowchart, all necessary requirements should be listed out in logical
order.
(b) The flowchart should be clear, neat and easy to follow. There should not be any room for
ambiguity in understanding the flowchart.
(c) The usual direction of the flow of a procedure or system is from left to right or top to
bottom.
(d) Only one flow line should come out from a process symbol.

(e) Only one flow line should enter a decision symbol, but two or three flow lines, one for
each possible answer, can leave the decision symbol.

<0 >0 <0 >0

=0 =0

(f) Only one flow line is used in conjunction with terminal symbol.

Start Stop
Algorithmic Problem Solving 1.7

(g) Write briefly within the standard symbols. If necessary, you can use the annotation sym-
bol to describe data or computational steps more clearly.

Calculation Part

(h) If the flowchart becomes complex, it is better to use connector symbols to reduce the
number of flow lines. Avoid the intersection of flow lines if you want to make it more
effective and better way of communication.
(i) Ensure that the flowchart has a logical start and stop.
(j) Validity of the flowchart can be tested by passing through it with a simple test data.

1.4.3 Advantages of flowcharts


•• It is easy to understand.
•• A problem can be analyzed easily with flowchart.
•• It gives clear idea of a program.
•• It acts as a guide during the program development.
•• It helps to clear the errors in coding.
•• It helps in maintenance of code.

Disadvantages of flow charts


•• It cannot be prepared for difficult program.
•• Alterations and modifications cannot be done easily.
•• It is not typed, so its preparation is little difficult.

Flowchart representation to add two numbers


Start

Declare variables num1, num2 and sum

Read num1 and num2

sum = num1+ num2

Display sum

Stop
1.8 Problem Solving and Python Programming

1.5 PROGRAMMING LANGUAGE


A computer is the ideal machine to execute computational algorithms because:
•• The computer can perform arithmetic operations (easily, quickly).
•• It can also perform an operation only when some condition is satisfied (using the
conditional branch instruction).

Types of languages used in computer programming


•• The machine language (or instruction code) consists of (binary) numbers that encode
instructions for the computer
•• Every computer (CPU) has its own machine language
•• (i.e., the instruction code 1 can encode a different instruction for different CPUs)

A machine language program looks like:


10110101
10101111
01010110
10110111
Assembler language or low level programming language
•• An assembler language consists of (English like) mnemonics
•• There is one mnemonic for each machine instruction of the computer

An assembler language program looks like:


start
add x, y <-- one assembler instruction
sub x, y <-- one assembler instruction
...
...
end

(ii) High level programming language


A high level programming language consists of (English-like) “people” language to simplify
the writing computer algorithms
•• A high level programming language allows the programmer to write sentences in this
language which can be easily translated into machine instructions
•• The sentences written in a high level programming language are called:
statements

A high level language program looks like:


main()
{
if ( x > y ) // One sentence (statement) in a high level prog. lang.
Algorithmic Problem Solving 1.9

{
max = x;
}
else
{
max = y;
}
.....
}
One statement in a high level programming language is usually translated into multiple
machine instruction that achieve the effect specified by the statement.

Some well-known programming languages


Name Application area
Fortran Scientific application (Formula trasslator)
Cobol Business application (Common Business Oriented Language)
C System application (successor of a language called “B”)
C++ System application (successor of the language “C”)
Java General purpose (a simplification of “C++”)
C# General purpose (another simplification of “C++”)
Perl Scripting language with many string processing capabilities
Python Scripting language using indentation as block denotation.

1.6 ALGORITHMIC PROBLEM SOLVING


Understand the problem

Decide on:
Computational means,
exact vs. approximate
solving, algorithm design technique

Design an algorithm

Prove correctness

Analyzing an Algorithm

Code the algorithm

Figure 1.4. Algorithmic Problem Solving


1.10 Problem Solving and Python Programming

(a) Understanding the Problem


Before designing an algorithm one has to understand completely the problem given.

An input to an algorithm specifies an instance of the problem the algorithm solves. It is


important to specify exactly the range of instances the algorithm needs to handle.

(b) Ascertaining the Capabilities of the Computational Device


Once a problem is understood completely, one need to ascertain the capabilities of the
computational device the algorithm is intended for.

Sequential algorithms: Instructions are executed one after the other, one operation at a
time. Accordingly, algorithms designed to be executed on such machines.

Parallel algorithms: The central assumption of the RAM model does not hold for some
newer computers that can execute operations concurrently, i.e., in parallel.

(c) Choosing between Exact and Approximate Problem Solving


The next principal decision is to choose how to solve the problem.
•• Solving the problem exactly is called an exact algorithm
•• Solving it approximately is called an approximation algorithm.

(d) Deciding on appropriate Data Structures


In the new world of object oriented programming, data structures remain crucially important
for both design and analysis of algorithms. Data structures can be defined as a particular scheme of
organizing related data items.

Algorithms + Data Structures = Programs

(e) Algorithm Design Techniques


An algorithm design technique is a general approach to solving problems algorithmically
that is applicable to a variety of problems from different areas of computing.

First, they provide guidance for designing algorithms for new problems, i.e., problems for
which there is no known satisfactory algorithm. Second, algorithms are the cornerstone of computer
science. Every science is interested in classifying its principal subject, and computer science is
no exception. Algorithm design techniques make it possible to classify algorithms according to
an underlying design idea; therefore, they can serve as a natural way to both categorize and study
algorithms.

f) Methods of Specifying an Algorithm


Once an algorithm is designed, one need to specify it in some fashion.
•• Free and also a step-by-step form
•• Pseudocode.
Algorithmic Problem Solving 1.11

These are the two options that are most widely used nowadays for specifying algorithms.

Pseudocode is a mixture of a natural language and programming language like constructs.


Pseudocode is usually more precise than natural language, and its usage often yields more compact
algorithm descriptions.

In the earlier days of computing, the dominant vehicle for specifying algorithms was a
flowchart, a method of expressing an algorithm by a collection of connected geometric shapes
containing descriptions of the algorithm’s steps. This representation technique has proved to be
inconvenient for all except very simple algorithms.

(g) Proving an Algorithm’s Correctness


Once an algorithm has been specified, it has to be proved for its correctness. That is, one
has to prove that the algorithm yields a required result for every legitimate input in a finite amount
of time.

A common technique for proving correctness is to use mathematical induction because an


algorithm’s iterations provide a natural sequence of steps needed for such proofs. Although tracing
the algorithm’s performance for a few specific inputs can be a very worthwhile activity, it can’t
prove the algorithm’s correctness conclusively. But in order to show that an algorithm is incorrect,
one need just one instance of its input for which the algorithm fails.

The notion of correctness for approximation algorithms is less straightforward than it is


for exact algorithms. For an approximation algorithm, we usually would like to show that the error
produced by the algorithm does not exceed a predefined limit.

(h) Analyzing an Algorithm


Efficiency is an important characteristic of any algorithm.

There are two kinds of algorithm efficiency:

Time efficiency, indicating how fast the algorithm runs Space efficiency, indicating how
much extra memory it uses.

Another desirable characteristic of an algorithm is simplicity. Because simpler algorithms


are easier to understand and easier to program; consequently, the resulting programs usually
contain fewer bugs. Sometimes simpler algorithms are also more efficient than more complicated
alternatives.

Yet another desirable characteristic of an algorithm is generality.

There are two issues here:


•• Generality of the problem the algorithm solves, and
1.12 Problem Solving and Python Programming

•• The set of inputs it accepts.


Sometimes it is easier to design an algorithm for a problem posed in more general terms.
There are situations, however, where designing a more general algorithm is unnecessary or difficult
or even impossible.As to the set of inputs, the main concern should be designing an algorithm that
can handle a set of inputs that is natural for the problem at hand.

If one is not satisfied with the algorithm’s efficiency, simplicity, or generality, one must
return to the drawing board and redesign the algorithm. In fact, even if one’s evaluation is positive,
it is still worth searching for other algorithmic solutions.

(i) Coding an Algorithm


Most algorithms are destined to be ultimately implemented as computer programs.
Programming an algorithm presents both a peril and an opportunity. The peril lies in the possibility
of making the transition from an algorithm to a program either incorrectly or very inefficiently.
Some influential computer scientists strongly believe that unless the correctness of a computer
program is proven with full mathematical rigor, the program cannot be considered correct.

As a practical matter, the validity of programs is still established by testing. Testing of


computer programs is an art rather than a science, but that does not mean that there is nothing in it
to learn.

Example 1:
Sum of two numbers.
Algorithm
Step 1 : Start
Step 2 : Input the value of A and B.
Step 3 : Find the sum of A and B.
sum=A+B
Step 4 : Print the value of sum
Step 5 : Stop.

Pseudocode
READ the value of variables A and B.
Find the sum.
sum = A + B.
WRITE the output of sum.
STOP
Algorithmic Problem Solving 1.13

Flowchart
Start

Read A, B

Sum = A + B

Print sum

Stop

Example 2:
Find the area and circumference of circle.
Algorithm
Step 1 : Start
Step 2 : Input the radius of the circle
Step 3 : Find the area and circumference using the formula
Area = 3.14 * r *r
Circumference = 2*3.14*r
Step 4 : Print the area and circumference of the circle.
Step 5 : Stop
Flowchart
Start

Read the radius r

Calculate
area = 3.14*r*r
Circumference = 2*3.14*r

Print area and


Circumference

Stop
1.14 Problem Solving and Python Programming

Pseudo code
READ the radius of the circle
Find the area and circumference of the circle using the formula
Area = 3.14*r*r
Circumference = 2*3.14*r
WRITE the Output of area and Circumference of the circle
Stop

Example 3:
Find the greatest of 3 numbers.
Algorithm
Step 1 : Start
Step 2 : Read the value of a, b, c
Step 3 : Compare the values of a,b and c.
Step 4 : If a is greater than b, compare a with c.
If a is greater than c then print a is big.
Step 5 : If a is not greater than b & c then compare b and c.
Step 6: If b is greater than c print b is big else print C is big.
Step 7 : Stop

Pseudocode :
READ the values of a, b, c
IF (a > b) && (a > c) THEN
WRITE a is big
ELSE
IF (b>c) THEN
WRITE b is big
ELSE
WRITE c is big
ENDIF
ENDIF
Stop
Algorithmic Problem Solving 1.15

Flowchart

Start

Read A, B

If No
Yes
(a>b) &&(a>c)

If No
Print a in big Yes
(b > c)

Print b in big Print c in big

Stop

Example 4:
Check whether the given number is even or odd.
Algorithm
Step 1 : Start

Step 2 : Read the value of n ;

Step 3 : If (n%2==0) then print it is an even number, else print it is an odd number

Step 4 :Stop

Pseudocode
READ the value of n
IF (n%2==0) THEN
WRITE n is even number
ELSE
WRITE n is odd number
ENDIF
Stop
1.16 Problem Solving and Python Programming

Flowchart

Start

Read n

If No
(n%2==0)

Yes
Print n in even Print n in odd

Stop

Example 5:
Find the factorial of a given number.
Algorithm
Step 1 : Start
Step 2 : Initialize r=0, sum=0
Step 3 : READ the value of n
Step 4 : If n>0 do the following else goto step 6
Step 4.1: r=n mod 10
Step 4.2 : sum=sum*10+r
Step 4.3 : n=n div 10
Step 5 : Goto step 4
Step 6 : Print sum
Step 7 : Stop

Pseudocode
Set initial sum=0, r=0
READ the value of n
WHILE (n>0)
r=n%10
sum=sum*10+r
Algorithmic Problem Solving 1.17

n=n/10
ENDWHILE
Repeat while until the condition fail
WRITE the sum
Stop

Flowchart:

Start

Initialize
r=0; sum =0

Yes While No
n>0

r=n%10
sum=sum*10+r
n=n/10

Print sum

Stop

1.7 SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS


Iteration and recursion are key Computer Science techniques used in creating algorithms
and developing software.

In simple terms, an iterative function is one that loops to repeat some part of the code, and
a recursive function is one that calls itself again to repeat the code.

Using a simple for loop to display the numbers from one to ten is an iterative process.
Solving the Eight Queens Problem is a simple recursive process.

Recursion is a problem solving approach by which a function calls itself repeatedly until
some specified condition has been satisfied. Recursion splits a problem into one or more simpler
versions of itself.
1.18 Problem Solving and Python Programming

Advantages of Recursive functions:


•• Recursion can produce simpler, more natural solutions to a problem
•• It is written with less number of statements
•• Recursive functions are effective where the terms are generated successively to compute
a value
•• It requires few variables which makes program clean
•• It is useful for branching processes.

Difference between recursion and iteration:


Recursion Iteration
Repetition is achieved through repeated Iteration is explicitly a repetition structure
function calls
Recursion terminates when a base case is Iteration terminates when the loop
recognized continuation test becomes false
Recursion causes another copy of the function Iteration normally occurs within a loop, so
and hence a considerable memory space is the extra memory assignment is omitted
occupied

Illustrative problems:
Find minimum number in a list
Program
lst = []
num = int(input('How many numbers: '))
for n in range(num):
numbers = int(input('Enter number '))
lst.append(numbers)
print("Maximum element in the list is :", max(lst), "\n Minimum element in the list is :",
min(lst))

Output :
Algorithmic Problem Solving 1.19

Insert a card in a list of sorted cards :


Program:
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)

Output:
[17, 20, 26, 31, 44, 54, 55, 77, 93]

Guess an integer number in a range :


Program:
import random
hidden = random.randrange(1, 201)
print(hidden)
guess = int(input("Please enter your guess: "))
if guess == hidden:
print("Hit!")
elif guess < hidden:
print("Your guess is too low")
else:
print("Your guess is too high")
The first thing is to load the random module. It has a method called randrange that can
generate an integer number in a given range. In our case we wanted to have a number that can be
1 .. 200 but because of the way the Python range works, we had to call the method with 201 as the
ranges in Python never include the upper boundary.
1.20 Problem Solving and Python Programming

1.8 TOWERS OF HANOI


Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective
of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

(1) Only one disk can be moved at a time.


(2) Each move consists of taking the upper disk from one of the stacks and placing it on
top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
(3) No disk may be placed on top of a smaller disk.

Program:
def TowerOfHanoi(n , from_rod, to_rod, aux_rod):
if n == 1:
print "Move disk 1 from rod",from_rod,"to rod",to_rod
return
TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)
print "Move disk",n,"from rod",from_rod,"to rod",to_rod
TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)
Output:
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Algorithmic Problem Solving 1.21

Move disk 1 from rod C to rod A


Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
UNIT - 2

DATA, EXPRESSIONS, STATEMENTS

2.1. INTRODUCTION: PYTHON


There are two ways to use the interpreter: interactive mode and script mode.

In interactive mode, type Python programs and the interpreter displays the result.

2.2. PYTHON INTERPRETER AND INTERACTIVE MODE


Interpreter
Python is an interpreted language because it is executed by an interpreter. Interpreter
takes high level program as input and executes what the program says. It processes the program
a minimum one at a time. It read lines and performs computations alternatively. The figure 2.1
explains the structure of an interpreter.

Source Code Interpreter Output

Figure. 2.1 Function of Interpreter

Compiler
A compiler reads the program and translates it completely to machine readable form called
object code or executable code before the program starts running. Once a program in compiled, the
program can be executed repeatedly without further translations. The figure 2.2 shows the structure
of a compiler.

Source Compiler Object Executor Output


Code
Code
Figure. 2.2 Function of Compiler
To execute the program code, the interpreter can be used. There are two different modes to
use the interpreter. 1. Interactive mode, 2. Script mode. In interactive mode, the program statements
can be typed in prompt, so the interpreter displays the result.

>>>1+1
2

The prompt >>> (chevron) indicates that the interpreter is ready.


2.2 Problem Solving and Python Programming

Interactive Mode
So far we have run Python in interactive mode, which means that one interact directly with
the interpreter. Interactive mode is a good way to get started, but if one is working with more than
a few lines of code, it can be clumsy.

The alternative is to save code in a file called a script and then run the interpreter in script
mode to execute the script.

By convention, Python scripts have names that end with .py.


•• To execute the script, in UNIX and windows type,
•• python filename.py # To execute the file
•• For larger programs, the program code can be stored as a script and execute it in the
future.

Example:
# first simple program

# To print Hello, World!

print ‘Hello, World!’

It prints Hello, World. In python printing statement uses the keyword print as in the above
mentioned format.

In Python 3, the syntax for printing is slightly different like this,

print (‘Hello, World!’)

The parenthesis indicates that the print is a function. The single quotation represents the
beginning and end of the text to be displayed.

For example, the script


print(1)
x=2
print(x)
produces the output
1
2

2.3 VALUES AND TYPES


A value is a basic thing that a program works with, like a letter or a number. Ex: 1,2 and
‘Hello, World!’.
Data, Expressions, Statements 2.3

The values belong to different data types. In Python, the standard data types available are:
(1) Numbers
(2) String
(3) List
(4) Tuple
(5) Dictionary

(i) Number data type


Number data type stores numerical values. It supports four numerical types.
(1) int (signed numbers like 10, -20)
(2) long (long integers represented in octal & hexadecimal like, ox3245 and 234L)
(3) float (Floating point real values like 3.45)
(4) complex (Complex numbers like, 7.32e-3j) [ordered pairs of real floating point numbers
represented by x ± jy, where x & y are real numbers and j is imaginary part.
(5) Boolean data type takes the two values: True and False.

Example:
print True # True is a Boolean value print False # False is a Boolean value.
>>>True and False # False
>>>False or True # True
>>> (30 > 45) or (27 < 30) # True
>>> not True # False
>>> not (3 > 4) # True
>>> 3 > 4 # False
>>> test = (3 > 4)
>>> test # False
>>> type(test) #<type ‘bool’>

(ii) String data type


Strings are amongst the most popular types in Python and it is an ordered sequence of
characters. We can create them simply by enclosing characters in quotes. Python treats single quotes
the same as double quotes. Creating strings is as simple as assigning a value to a variable.

The substring access is possible through the slicing operator ([] or [:]). The string index 0
represents beginning of the string whereas, index -1 represents ending of the string. The following
examples illustrate the string and substring accesses.
2.4 Problem Solving and Python Programming

Example:
#str – string variable (explained later in this chapter) assigned with a value
str= ‘Hello, World!’

Code Comment Result


print str # prints complete string Hello, World!
print str[0] # prints first character of the string H
print str[-1] #prints last character of the string !
print str[1:5] # prints character starting from index 1 to 4 ello
# prints str[start_at : end_at-1]
print str[2:] #prints string starting at index 2 till end of the string llo, World!
print str * 2 # asterisk (*) -is the repetition operator. Prints the Hello, World!
string two times. Hello, World!
print str + “Hai” # prints concatenated string Hello, World! Hai

(iii) List data type


Lists are the most significant compound data types which contain elements of various types.
A List can hold items of different data types. The list is enclosed by square brackets [] where the
items are separated by commas. Like string data type, the list values can be accessed using the slice
operator ( [] or [ : ]). The index 0 represents beginning of the list whereas, index -1 represents ending
of the list. The following example illustrates list accesses.

Lists are mutable, which means we can change their elements.

Example:
list1=[‘abcd’, 345, 3.2,’python’, 3.14]
list2=[234, ‘xyz’]

Code Comment Result


print list1 # prints complete list [‘abcd’, 345, 3.2,’python’,
3.14]
print list1[0] # prints first element of the list abcd
print list1[-1] #prints last element of the list 3.14
print list1[1:3] # prints elements starting from index 1 to 2 [345, 3.2]
# prints list1[start_at : end_at-1]
print list1[2:] #prints list starting at index 2 till end of the [3.2, ‘python’, 3.14]
list
print list 2 * 2 # asterisk (*) -is the repetition operator. Prints [‘abcd’, 345, 3.2, ‘python’,
the list two times. 3.14, 234, ‘xyz’]
Data, Expressions, Statements 2.5

print list1 + list2 # prints concatenated lists [‘abcd’, 345, 3.2,’python’,


3.14, 234, ‘xyz’]

(iv) Tuple data type


Tuple is another sequence data type similar to list. A tuple consists of a number of values
separated by commas and enclosed within parentheses. Unlike list, the tuple values cannot be
updated. They are treated as read-only lists. The following example explains the tuple element
access.

Example:
tuple1= (‘abcd’, 345 , 3.2,’python’, 3.14)

tuple2= (234, ‘xyz’)

Code Comment Result


print tuple1 # prints complete tuple1 (‘abcd’, 345, 3.2, ’python’,
3.14)
print tuple1[0] # prints first element of the tuple1 abcd
print tuple1[-1] #prints last element of the tuple1 3.14

print tuple1[1:3] # prints elements starting from index 1 to 2 (345, 3.2)


# prints tuple1[start_at : end_at-1]

print tuple1[2:] #prints tuple1 starting at index 2 till the (3.2, ‘python’, 3.14)
end
print tuple 2 * 2 # asterisk (*) -is the repetition operator. (234, 'xyz', 234, 'xyz')
Prints the tuple2 two times.
print tuple1 + # prints concatenated tuples (‘abcd’, 345, 3.2,’python’,
tuple2 3.14, 234, ‘xyz’)

(v) Dictionary data type


Dictionary data type is a kind of hash table. It contains key-value pairs. A dictionary key
can be almost any python type, usually numbers or strings. Values can be arbitrary python object.
Dictionaries are enclosed by curly braces {} and values can be assigned and accessed using square
brackets []. The following example explains the dictionary element access.

dict1= {‘name’: ‘ABCD’ , ‘code’ : 6734 , ‘dept’ : ‘Engg’}


dict2= {}
dict2 [‘rollno’] = “II-ITA24”
2.6 Problem Solving and Python Programming

Code Comment Result


print dict1 # prints complete dictionary { ‘dept’: ‘Engg’, ‘code’:6734,
‘name’ : ‘ABCD’}
print dict1.keys() # prints all keys of dictionary { ‘dept’, ‘code’, ‘name’}

print dict1.values #prints all values of dictionary {‘Engg’, 6734, ‘ABCD’}


print dict2[‘rollno’] # print the value for the key rollno II-ITA24

2.4 VARIABLE
Variable is an identifier that refers to a value. While creating a variable, memory space is
reserved in memory. Based on the data type of a variable, the interpreter allocates memory. The
assignment statements are used to create new variables and assign values to them.
>>>msg= ‘ Hello, World!’
>>> n=12
>>> pi=3.14
The first statement creates a variable, msg and assigns ‘Hello, World!’ to it. The second
statement creates the variable, n assigns 12 to it. The third statement creates the variable, pi and
assigns the value 3.14.

Variable names can contain both letters and numbers, but they do not start with a number.
The underscore character ( _ ) can be used in variable names . In addition to variables, Python has
31 keywords.

and del from not while


as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try
Table 2.1. Python keywords

Python Identifiers
Identifier is the name given to entities like class, functions, variables etc. in Python. It helps
differentiating one entity from another.

Rules for writing identifiers


(1) Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z)
or digits (0 to 9) or an underscore (_). Names like myClass, var_1 and print_this_to_
screen, all are valid examples.
Data, Expressions, Statements 2.7

(2) An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
(3) Keywords cannot be used as identifiers.
(4) We cannot use special symbols like !, @, #, $, % etc. in our identifier.
(5) Identifier can be of any length.

2.5 EXPRESSIONS AND STATEMENTS


An expression is a combination of values, variables and operators. A value and a variable,
itself considered as an expression.

Example:
17 #expression
X #expression
X+17 #expression

A statement is a code that ends with a new line. So far, we have seen two kinds of statements:
print and assignment. Python allows the use of line continuation character (\) to denote that the
line should continue.

Example:
Total = mark1+ \
mark2+ \
mark3
But the statements contained within [], {} or () brackets do not need to use line continuation
characters. For example,

Item= [‘item1’, item2’, ‘item3’, ‘item4’, ‘item5’]

2.5.1 Assigning Values in Python


In Python both numerals and strings are considered as values. For e.g. 5, 28, 3.76 ,“Hai” are
all values. They are also called as literals. Literals can be of any type such int, float or string.

For example,
5,28 are of type int.
3.76 is float
“Hai” is of type string.

2.5.2 Variable Declaration


In python, interpreter automatically detects the type by the data to which it is assigned. For
assigning values “=” is used.
2.8 Problem Solving and Python Programming

Examples of Variable Declaration


>>>X= 10 # x is an integer
>>>Y=15.7 # y is float
>>>Z=”Welcome to Python” # Z is a string

2.5.3 Multiple Assignments


Multiple assignments are allowed in a single statement in Python language.

For example,
>>> a, b, c = 2, 4, 6, “Hai”

If all the variables possess same value, then it can be represented as follows:
>>>a=b=c = “5”

Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation.

A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to one's choice , but it must be consistent throughout
that block.

Generally four whitespaces are used for indentation and is preferred over tabs. Here is an
example.

2.6 OPERATORS
An operator is a special symbol that asks the compiler to perform particular mathematical
or logical computations like addition, multiplication, comparison and so on. The values that are
applied to the operator are called operants. For eg, in the expression 4 + 5, 4 and 5 are operands
and + is an operator.

The following tokens are operators in python:


+ – * ** / // %
<< >> & | ^ ~
< > <= >= == != <>
Data, Expressions, Statements 2.9

2.6.1 Types of Operator


Python language supports the following types of operators.
•• Arithmetic Operators
•• Comparison (Relational) Operators
•• Assignment Operators
•• Logical Operators
•• Bitwise Operators
•• Membership Operators
•• Identity Operators
•• Unary arithmetic Operators

Arithmetic Operators

Operator Description
+ Addition Adds two operands.
- Subtraction Subtracts second operand from first operand.
* Multiplication Multiplies two operands.
/ Division Divides first operand by second operand.
% Modulus Divides first operand by second operand and returns the remainder
** Exponent Performs exponential (power) calculation
// Floor Division Division of operands in which the quotient without fraction is returned
(Integer Division) as a result.

Sample Code:
a = 21
b = 10
c=0
c=a+b
print “Result of addition “, c
c=a-b
print “Result of subtraction “, c
c=a*b
print “Result of multiplication “, c
c=a/b
2.10 Problem Solving and Python Programming

print “Result of division “, c


c=a%b
print “Result of modulus “, c
a=2
b=3
c = a**b
print “Result of exponentiation “, c
a = 10
b=5
c = a//b
print “Result of floor division “, c

Sample Output:
Result of addition 31
Result of subtraction 11
Result of multiplication 210
Result of division 2
Result of modulus 1
Result of exponentiation 8
Result of floor division 2

Comparison (Relational) Operators


These operators compare the values of their two operands and determine the relationship
among them.
Operator Description
== If the values of two operands are equal, then this operator returns true.
!= If the values of two operands are not equal, then this operator returns true.
> If the value of first operand is strictly greater than the value of second operand, then
this operator returns true.
< If the value of first operand is strictly smaller than the value of second operand,
then this operator returns true.
>= If the value of first operand is greater than or equal to the value of second operand,
then this operator returns true.
<= If the value of first operand is smaller than or equal to the value of second operand,
then this operator returns true.
Data, Expressions, Statements 2.11

Sample Code and Output:


>>>4 == 4
True
>>>4 != 4
False
>>>4 < 5
True
>>>4 >= 3
True
>>>”A” < “B”
True
>>>

Assignment Operators
Operator Description
= Assigns values from right side operand to left side operand.
+= Performs addition using two operands and assigns the result to left side
operand.
-= Subtracts right side operand from the left side operand and assigns the
result to left side operand.
*= Performs multiplication using two operands and assigns the result to left
side operand.
/= Divides left side operand by the right side operand and assigns the result to
left side operand.
%= Finds modulus using two operands and assigns the result to left side operand.
**= Performs exponential calculation and assigns the result to the left side
operand.
//= Performs floor division and assigns the result to the left side operand

Sample Code:
a = 10
b=5
c=a
print “c is “,c
c=a+b
print “c is “, c
c += a # c=c+a
2.12 Problem Solving and Python Programming

print “c is “, c
c -=a # c=c-a
print “c is “, c
c *= a # c=c*a
print “c is “, c
c /= a # c=c/a
print “c is “, c
c =2
c %= a # c=c%a
print “c is “, c
c **= a # c = c ** a
print “c is “, c
c //= a # c = c // a
print “c is “, c

Sample Output:
c is 10
c is 15
c is 25
c is 15
c is 150
c is 15
c is 2
c is 1024
c is 102

Logical Operators
Following table shows all the logical operators supported by Python:
Operator Description
and Logical AND returns true, if and only if both operands are true.
or Logical OR returns true, if any of the two operands is true.
not Logical NOT returns the logical negation of its operand.
Here, any nonzero number is interpreted as true and zero is interpreted as false. Both the
and operator and the or operator expect two operands. not operator operates on a single operand.

The behaviour of each logical operator is specified in a truth table for that operator.
Data, Expressions, Statements 2.13

Sample Code:
a=True
b=False
print a and b
print a or b
print not a
Sample Output:
False
True
False

Bitwise Operators
Bitwise operators perform bit by bit operations and explained as:
Operator Description
& Performs Bitwise AND operation between two the operands.
| Performs Bitwise OR operation between two the operands.
^ Performs Bitwise XOR (exclusive OR) operation between two the operands.
~ Performs Bitwise 1’s complement on a single operand.
<< Shifts the first operand left by the number of bits specified by the second operand
(Bitwise Left Shift).
>> Shifts the first operand right by the number of bits specified by the second operand
(Bitwise Right Shift).

Sample Code:
a = 60 # 60 = 0011 1100
b = 26 # 13 = 0001 1010
c = a & b; # 24 = 0001 1000
print “Result of Bitwise AND is “, c
c = a | b; # 62 = 0011 1110
print “Result of Bitwise OR is “, c
c = a ^ b; # 38 = 0010 0110
print “Result of Bitwise XOR is “, c
c = ~a; # -61 = 1100 0011
print “Result of Bitwise Ones Complement is “, c
c = a << 2; # 240 = 1111 0000
print “Result of Bitwise Left Shift is “, c
c = a >> 2; # 15 = 0000 1111
print “Result of Bitwise Right Shift is “, c
2.14 Problem Solving and Python Programming

Sample Output:
Result of Bitwise AND is 24
Result of Bitwise OR is 62
Result of Bitwise XOR is 38
Result of Bitwise Ones Complement is -61
Result of Bitwise Left Shift is 240
Result of Bitwise Right Shift is 15

Membership Operators
Membership operators test for membership in a sequence, such as strings, lists, or tuples
and explained as:

Operator Description
in Evaluates to true if it finds a variable in the specified sequence and false otherwise.
not in Evaluates to true if it does not find a variable in the specified sequence and false
otherwise.

Sample Code:
a=6
b=2
list = [1, 2, 3, 4, 5 ];
print a in list
print a not in list
print b in list
print b not in list

Sample Output:
False
True
True
False

Identity Operators
Identity operators compare the memory locations of two objects. They are explained below:
Operator Description
is Returns true if both operands point to the same object and false otherwise.
is not Returns false if both operands point to the same object and true otherwise.
Data, Expressions, Statements 2.15

Sample Code:
a = 20
b = 20
print a is b
print id(a) == id(b)
print a is not b
b=30
print a is b
print a is not b
print id(a) == id(b)

Sample Output:
True
True
False
False
True
False

Unary arithmetic operators

Operator Description
+ Returns its numeric argument without any change.
- Returns its numeric argument with its sign changed.

Sample Code:
a = 10
b = +a
print b
c = -a
print c
Sample Output:
10
–10
2.16 Problem Solving and Python Programming

2.6.2 Operator precedence


When more than one operator appears in an expression, the order of evaluation depends on
the rules of precedence. For mathematical operators, Python follows mathematical convention. The
acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition, Subtraction)
is a useful way to remember the rules.

The following table summarizes the operator precedence in Python, from the highest
precedence to the lowest precedence. Operators in the same box have the same precedence and
group from left to right (except for comparisons statements).

Operator Description Associativity


(expressions...) Binding or tuple display left to right
[expressions...] list display
{key: value...} dictionary display
'expressions...' string conversion
x[index] Subscription left to right
x[index:index] Slicing
x(arguments...) Call
x.attribute Attribute reference
** Exponentiation right-to-left
+x Unary plus left to right
-x Unary minus
~x Bitwise NOT
* Multiplication left to right
/ Division
// Floor division
% Remainder 
+ Addition left to right
- Subtraction
<<, >> Bitwise Left Shift and Right left to right
Shift
& Bitwise AND left to right
^ Bitwise XOR left to right
| Bitwise OR left to right
in, not in Membership tests Chain from left to right
is, is not Identity tests
<, <=, >, >=, <>, !=, == Comparisons
not  Boolean NOT left to right
and Boolean AND left to right
or Boolean OR left to right
Data, Expressions, Statements 2.17

Examples:
4 * (6-3) is 12, and (1+2)**(6-3) is 27.
3**1+1 is 4, not 9.
2*1**4 is 2, not 16.
4*6-2 is 22, not 16.
4+2/2 is 5, not 3.
4/2*2 is 4, not 1.

2.7 COMMENTS
Comments are the non-executable statements explain what the program does. For large
programs it often difficult to understand what it does. The comment can be added in the program
code with the symbol #.
Example:
print ‘Hello, World!’ # print the message Hello, World!; comment
v=5 # creates the variable v and assign the value 5; comment

2.8. MODULES AND FUNCTIONS


2.8.1 Modules
A Module holds some definitions and statements. Python puts some statements and
definitions in a file and that can be used in the interpreter. Such a file is defined as module and
contains a name with a suffix .py extension. A module can also be imported using the statement
“import module name”. A module name is considered as a global variable value as __name__.
Python also uses some built in modules.
Eg. >>Import math
>>>Print (math.sqrt (81))

2.8.2 Function Definition and Use


A function is a group of statements that perform a specific task. If a program is large, it
is difficult to understand the steps involved in it. Hence, it is subdivided into a number of smaller
programs called subprograms or modules. Each subprogram specifies one or more actions to be
performed for the larger program. Such subprograms are called as functions. Functions may or may
not take arguments and may or may not produce results.

In Python ,there are two types of functions in python. They are :


(i) Built –in function: These are predefined functions usually a part of Python packages
and libraries such as raw_input (), type (), float (), int() etc.,, are some of the built-in
functions. Built-in functions are treated as reserved words (not used as variable names)
(ii) User defined function: Functions that are defined by the users are treated as user defined
functions.
2.18 Problem Solving and Python Programming

(i) Built-in/Pre-defined function


Built-in functions are functions already built into Python interpreter and are readily available
for use.

Example:
print() Print objects to the stream.
Reads a line from input, converts it to a string (stripping a trailing newline), and
input()
returns that.
abs() Return the absolute value of a number.
len() Return the length (the number of items) of an object.

Program to find the ASCII value of the given character.


c = input(“Enter a character”)
print(“ASCII value of “ +c+ “is”+ord(c))

Sample Input/Output:
p

ASCII value of p is 112


ord() function convert a character to an integer (ASCII value). It returns the Unicode code
point of that character.

Type conversion functions


Python provides built-in functions that convert values from one type to another.
Function Converting what to what Example
>>> int(‘2014’)
2014
int() string, floating point → integer
>>> int(3.141592)
3
>>> float(‘1.99’)
1.99
float() string, integer → floating point number
>>> float(5)
5.0
>>> str(3.141592)
integer, float, list, tuple, dictionary ‘3.141592’
str()
→ string >>> str([1,2,3,4])
‘[1, 2, 3, 4]’
>>> list(‘Mary’) # list of characters in ‘Mary’
[‘M’, ‘a’, ‘r’, ‘y’]
list() string, tuple, dictionary → list
>>> list((1,2,3,4)) # (1,2,3,4) is a tuple
[1, 2, 3, 4]
Data, Expressions, Statements 2.19

>>> tuple(‘Mary’)
(‘M’, ‘a’, ‘r’, ‘y’)
tuple() string, list → tuple
>>> tuple([1,2,3,4]) # [ ] for list, ( ) for tuple
(1, 2, 3, 4)
>>> age = 21
>>> sign = ‘You must be ‘ + age + ‘Years old’
Many Python functions are sensitive to the type of data. For example, you cannot concatenate
a string with an integer. If you try, it will result in following error.

Traceback (most recent call last):


File “<pyshell#71>”, line 1, in <module>
sign = ‘You must be ‘ + age + ‘years old’
TypeError: cannot concatenate ‘str’ and ‘int’ objects

For the example above, use the str() conversion function to convert integer to string data
type.
>>> age = 21
>>> sign = “You must be “ + str(age) + “Years old”
>>>sign

Sample Output:
You must be 21 Years old

Examples using Built-in functions for type conversion


Program Code Output
Converting float to int
>>>print(3.14, int(3.14)) 3.14 3
>>>print(3.9999, int(3.9999)) 3.9999 3
>>>print(3.0, int(3.0)) 3.0 3
>>>print(-3.999, int(–3.999)) –3.999 –3
Converting string to int
>>>print("2345", int("2345")) 2345 2345
>>>print(int("23bottles")) Error :
ValueError: invalid literal for int() with
base 10: '23bottles'
Converting int to string
>>>print(str(17)) 17
2.20 Problem Solving and Python Programming

Converting float to string


>>>print(str(123.45))
>>>print(type(str(123.45))) 123.45

Converting list to tuple


>>>fruits = ['apple', 'orange', 'grapes', <class 'str'>
'pineapple'] ('apple', 'orange', 'grapes', 'pineapple')
>>>print(tuple(fruits)) ('P', 'y', 't', 'h', 'o', 'n')
>>>print(tuple('Python'))
Converting tuple to list
>>>print(list(‘Python’)) ['P', 'y', 't', 'h', 'o', 'n']

Math functions
Math and cmath are mathematical modules available in Python to support familiar
mathematical functions. A module is a file that contains a collection of related functions. Before
using built-in math functions, import math module.

>>>import math

It will create a module object named math which contains functions and variables defined in
the module. Some of the familiar math functions are listed in the table below.

Function Description Example Output


abs(n) Return the absolute abs(–99) 99
value of a number(n)
round(n,d) Round a number(n) to round(3.1415,2) 3.14
a number of decimal
points(d)
floor(n) Round down to math.floor(4.7) 4.0
nearest integer
ceil(n) Round up to nearest math.ceil(4.7) 5.0
integer
pow(n,d) Return n raised to the math.pow(10,3) 1000.0
power d
sqrt(n) Returns the square math.sqrt(256) 16.0
root of number(n)
Data, Expressions, Statements 2.21

fsum(iterable) Return an accurate sum([.1, .1, .1, .1, .1, 0.99999999999999


floating point sum of .1, .1, .1, .1, .1])
values in the iterable fsum([.1, .1, .1, .1, .1,
.1, .1, .1, .1, .1])

1.0
factorial(n) Return n factorial math.factorial(5) 120
gcd(n,m) Return greatest math.gcd(10,125) 5
common divisior of
(n,m)
trunc(x) Return the real math.trunc(1.999) 1
value  x truncated to
an integral
sin(x), cos(x), Return the arc sine, math.sin(math.pi/4)  0.7071067811865476
tan(x) cosine, tangent of x, math.cos(math.pi) –1.0
in radians.
math.tan(math.pi/6) 0.5773502691896257

Mathematical Constants
•• math.pi
The mathematical constant π = 3.141592..., to available precision.
•• math.e
The mathematical constant e = 2.718281..., to available precision.

(ii) User defined function


The functions defined by the users according to their requirements are called user-defined
functions. The users can modify the function according to their requirements.
Example:
multiply(), sum_of_numbers(), display()

2.8.3 Defining a Function


Functions in python are defined using the block keyword def followed by the function name
and parentheses ( ( ) ). Function definition includes:
(1) A header, which begins with a keyword def and ends with a colon.
(2) A body consisting of one or more Python statements each indented the same amount – 4
spaces is the Python standard – from the header.

Syntax:
def function_name( parameters ):
“function_docstring”
2.22 Problem Solving and Python Programming

function_suite
return [expression]
The code block within every function starts with a colon (:) and is indented. The first
statement of a function can be an optional statement - the documentation string of the function or
docstring. The statement return [expression] exits a function, and optionally it returns the result of
the function. The rules for function names are the same as for variable names: letters, numbers and
some punctuation marks are legal, but the first character can’t be a number. Keywords should not be
used as function name. To avoid confusion, use different names for functions and variables.

2.8.4 Calling a Function


A function can be executed by calling it from another function or directly from the Python
prompt by its name.

Syntax:
function_name(parameters)
Function to display Welcome message.
def display():
print “Welcome!!!”
>>>display()
Sample output:
Welcome!!!
The first line of the function definition is called the header; the rest is called the body. The
header has to end with a colon and the body has to be indented. By convention, the indentation is
always four spaces. In this example, the function name is display().The empty parentheses after the
name indicate that this function doesn’t take any arguments.

Function to find the biggest of three numbers.


def great(no1,no2,no3):
if (no1>no2) and (no1>no3):
return no1
elif (no2>no3):
return no2
else:
return no3
n1=input(“Enter first number”)
n2=input(“Enter second number”)
n3= input(“Enter third number”)
result=great(n1,n2,n3)
print result, “is bigger”
Data, Expressions, Statements 2.23

Sample Input/Output:
Enter first number 10
Enter second number 5
Enter third number 25
25 is bigger
In this example, the function name is great().It takes three parameters and return the greatest
of three. input() reads input value from the user. The function is invoked by calling great(n1,n2,n3).
print() displays the output. The strings in the print statements are enclosed in double quotes.

2.8.5 Uses of Function


def add(a,b):
return (a+b)
def sub(a,b):
return (a-b)
def calculate():
a=input(“Enter first number”)
b=input(“Enter second number”)
result=add(a,b)
print result
result=sub(a,b)
print result
return
This program contains three function definitions: add(), sub(), and calculate(). Function
definitions are executed to create function objects. The statements inside the function do not get
executed until the function is called, and the function definition generates no output. Function must
be created before execution i.e. function definition has to be executed before the first time it is
called.

2.8.6 Advantages of Functions


•• Decomposing larger programs in to smaller functions makes program easy to understand,
maintain and debug.
•• Functions developed for one program can be reused with or without modification when
needed.
•• Reduces program development time and cost.
•• It is easy to locate and isolate faulty function.
2.24 Problem Solving and Python Programming

2.9 FLOW OF EXECUTION


Flow of execution specifies the order in which statements are executed. Program execution
starts from first statement of the program. One statement is executed at a time from top to bottom.
Function definitions do not alter the flow of execution of the program, and the statements inside the
function are not executed until the function is called. When a function is called, the control flow
jumps to the body of the function, executes the function, and return back to the place in the program
where the function call was made. Python is good at keeping track of where it is, so each time a
function completes, the program picks up where it left off in the function that called it. When it gets
to the end of the program, it terminates.

2.10 PARAMETERS AND ARGUMENTS


Arguments are the values provided to the function during the function call. Parameters
are name used inside the function definition to refer to the value passed as an argument. Inside the
function, the value of arguments passed during function call is assigned to parameters.

Function to raise a number to given power


import math # This will import math module
>>>def raise(no,power):
print math.pow(no,power)
>>>a=100
>>>b=2
>>>raise(a,b)
>>>10000
The function raise() assign the argument a, b to parameters no, power.
>>>raise(30,3)
>>>27000
The function raise() assign the values 30, 3 to parameters no, power.
In this example, the arguments used in function call raise() are a, b and their values are
assigned to parameters no, power.

2.10.1 Functions with no arguments


The empty parentheses after the function name indicate that this function doesn’t take any
arguments.

Function to display PI value.


import math
>>>def show_PI():
print math.pi
>>>show_PI()
Data, Expressions, Statements 2.25

Sample output:
3.141592653589793

2.10.2 Functions with arguments


Functions may also receive arguments (variables passed from the caller to the function).
Arguments in function call are assigned to function parameters.

Function to calculate area of a circle.


import math
>>>def area_of_circle(r):
a = r * r * math.pi
print “Area of Circle:”, a
>>>radius=input(“Enter Radius:”)
>>>area_of_circle(radius)

Sample output:
Enter Radius:6
Area of Circle:113.04

2.10.3 Functions with return value


Functions may return a value to the caller, using the keyword- ‘return’.

Function to calculate factorial of a given number.


def factorial(num):
fact=1
i=1
if num==0:
return 1
else:
for i in range(1,num+1):
fact=fact*i
return fact
no=input(“Enter a number”)
print(factorial(no))

Sample input/output:
Enter a number:5
120
2.26 Problem Solving and Python Programming

2.11 ILLUSTRATIVE PROGRAMS


2.11.1 Function to exchange the values of two variables
def swap(a,b): # function definition for swapping
tmp=a
a=b
b=tmp
print ‘After Swap: n1=”,a, “n2=”,b
return
n1=input(“Enter first number”)
n2=input(“Enter second number”)
print ‘Before Swap: n1=”,n1, “n2=”,n2
swap(n1,n2) # function call

Sample input/output:
Enter first number1
Enter second number11
Before Swap: n1= 1 n2= 11
After Swap: n1= 11 n2= 1

2.11.2 Python program to test for leap year


Note: A leap year is divisible by four, but not by one hundred, unless it is divisible by four
hundred.
def leapyr(yr): # function definition
if yr%4==0 and yr%100!=0 or yr%400==0: # condition check for leap year
print ‘Leap Year’
else:
print ‘Not a Leap Year’
return
year=input(“Enter a year”)
leapyr(year) # function call

Sample input/output:
Enter a year1900
Not a Leap Year
Data, Expressions, Statements 2.27

2.11.3 Python program to test for leap year using calendar module
Python provides this functionality already in the library module ‘calendar’.
import calendar
def leapyr(yr):
if(calendar.isleap(yr)): # Using built-in function to check for leap year
print ‘Leap Year’
else:
print ‘Not a Leap Year’
return
year=input(“Enter a year”)
leapyr(year)

2.11.4 Python function to sum all the numbers in a list


def sum(numbers):
total=0
for x in numbers: # Loop through number
total+=x
return total
print(sum((1,2,3,4,5)))

Sample output:
15

2.11.5 Python program to reverse a string


def string_reverse(str1):
rstr1= “”
index=len(str1)
while index>0:
rstr1+=str1[index-1]
index=index-1
return rstr1
print “Reverse String:”, string_reverse(“Python”)

Sample output:
Reverse String:nohtyP
2.28 Problem Solving and Python Programming

2.11.6 Python function to check whether a number is in a given range


def test_range(n):
if n in range(1,10): # Loop through range of number from 1 upto 10
print “No. is between 1 and 10”
else:
print “No. is not between 1 and 10”
no=input(“Enter a no.”)
test_range(no)

Sample input/output:
Enter a no. 10
No. is not between 1 and 10
Enter a no. 4
No. is between 1 and 10

2.11.7 Python program to print the even numbers from a given list
def print_even(l): # l represents list of values
for n in l:
if n % 2 == 0:
print ‘\n’, n
return
print_even([1, 2, 3, 4, 5, 6, 7, 8, 9])

Sample output:
2
4
6
8

2.11.8 Function that circulates/rotates the list values for given number of times (order)
def rotate(l,order):
for i in range(0,order):
j=len(l)-1
Data, Expressions, Statements 2.29

while j>0:
tmp=l[j]
l[j]=l[j-1]
l[j-1]=tmp
j=j-1
print i, ‘rotation ’,l
return
l=[1,2,3,4,5]
rotate(l,3)
Sample output:
0 rotation: [5, 1, 2, 3, 4]
1 rotation: [4, 5, 1, 2, 3]
2 rotation: [3, 4, 5, 1, 2]

2.11.9 Find the distance between two points (xc,yc) and (xp,yp).
import math
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result
xc=int(input("Enter xc"))
yc=int(input("Enter yc"))
xp=int(input("Enter xp"))
yp=int(input("Enter yp"))
print (distance(xc,yc,xp,yp))

Sample input/output:
Enter xc 2
Enter yc 2
Enter xp 4
Enter yp 4
2.82
2.30 Problem Solving and Python Programming

SOME MORE EXAMPLES:


Function that takes a number as a parameter and check the number is prime or not
Note : A prime number (or a prime) is a natural number greater than 1 and that has no
positive divisors other than 1 and itself.
def test_prime(n): # function that returns boolean value
if(n==1):
return False
elif(n==2):
return True
else:
for x in range(2,n):
if(n%x==0):
return False
return True
no=input(“Enter a number”)
if(test_prime(no)):
print no, ‘is Prime’
else:
print no, ‘is not Prime’
Sample output:
Enter a number9
9 is not Prime
Enter a number11
11 is Prime

Function to check whether a number is perfect or not


Example : The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors,
and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: (
1 + 2 + 3 + 6 ) / 2 = 6.
def perfect_number(n): # function definition
sum = 0
for x in range(1, n):
if n % x == 0:
sum += x
return sum
Data, Expressions, Statements 2.31

no=input(“Enter a number”)
sum=perfect_number(no) # function call
if(sum==no):
print ‘Perfect number’
else:
print ‘Not a Perfect number’

Sample input/output:
Enter a number5
Not a Perfect number
Enter a number6
Perfect number

Function that checks whether a passed string is palindrome or not


def isPalindrome(string):
left_pos = 0
right_pos = len(string) - 1
while right_pos >= left_pos:
if string[left_pos] != string[right_pos]:
return False
left_pos += 1
right_pos -= 1
return True
str=raw_input(“Enter a string:”) #use raw_input() to read verbatim string entered
by user
if(isPalindrome(str)):
print str, ‘is a Palindrome’
else:
print str, ‘ is not a Palindrome’

Sample input/output:
Enter a string:madam
madam is a Palindrome

Function that checks whether a number is palindrome or not


def Palindrome_Number():
no = input(“Enter a Number:”)
2.32 Problem Solving and Python Programming

q=no
rev = 0
while(q!=0): # loop for reverse
rev = q % 10 + rev * 10
q = q / 10
if( rev == no):
print(‘%d is a palindrome number’ %no)
else:
print(‘%d is not a palindrome number’ %no)

Sample input/output:
Enter a Number121
121 is a palindrome number
UNIT – 3

CONTROL FLOW

3.1 CONDITIONALS: BOOLEAN VALUES AND OPERATORS


A boolean expression is an expression that is either true or false. The following examples
use the operator ==, which compares two operands and produces True if they are equal and False
otherwise:
>>>5 == 5
True
>>>5 == 6
False

True and False are special values that belong to the type bool; they are not strings:
type(True)
<class 'bool'>

The == operator is one of the relational operators; the others are given in the following table:
x != y x is not equal to y
x >y x is greater than y
x <y x is less than y
x>=y x is greater than or equal to y
X<=y x is less than or equal to y
Although these operations are probably familiar to you, the Python symbols are different
from the mathematical symbols. A common error is to use a single equal sign (=) instead of a double
equal sign (==). Remember that = is an assignment operator and == is a relational operator. There
is no such thing as =< or =>.

3.2 OPERATORS
Operators are the constructs (operator) which can manipulate the value of operands.

Consider the expression 4 + 5 = 9.

Here, 4 and 5 are called operands and + is called operator.


3.2 Problem Solving and Python Programming

Types of Operators
Python language supports the following types of operators.
(i) Arithmetic Operators
(ii) Comparison (Relational) Operators
(iii) Assignment Operators
(iv) Logical Operators
(v) Bitwise Operators
(vi) Membership Operators
(vii) Identity Operators

(i) Arithmetic Operators


It provides some arithmetic operators which perform that task of arithmetic operations in
Python. The following table source, the arithmetic operators.

Let us consider the value of a = 10, b = 20

Example
Operation Meaning Description
(a=10, b=20)
+ Addition Adds values on both side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left a – b = -10
hand operand
* Multiplication Multiplies values on both side of the a * b = 200
operator
/ Division Divides left hand operand by right hand b/a=2
operand
% Modulus Divides left hand operand by right hand b%a=0
operand and returns remainder
** Exponent Performs exponential (power) a**b =10 to the power 20
calculation on operators.
// Floor Division The division that results into whole 9//2 = 4 and 9.0//2.0 = 4.0,
number adjusted to the left in the number -11//3 = -4, -11.0//3 =-4.0
live.

Example 1 :
(1) Integer arithmetic
days = int(input(“Enter days: “))
months = days / 30
days = days % 30
Control Flow 3.3

print(“Months = %d Days = %d” % (months, days))

Output:
Enter days: 265
Months = 8 Days = 25

Example 2 :
days = int(input(“Enter days: “))
print(“Months = %d Days = %d” % (divmod(days, 30)))
The divmod(num1, num2) function returns two values , first is thedivision of num1 and
num2 and in second the modulo of num1 and num2.

(ii) Comparison Operators


These operators compare the values on either sides of them and decide the relation among
them. They are also known as Relational operators and are given in the following table.

Example
Operation Meaning Description
(a=10, b=20)
== Equal to If the values of two operands are equal, (a == b) is not true.
then the condition becomes true.
!= Not equal If the values of two operands are not equal, a – b = -10
then the condition becomes true.
> Greater than If the value of left operand is greater than (a > b) is not true
the value of the operand, then the condition
becomes true.
< Less than If the value of left operand is less than the (a < b) is not true
value of the operand, then the condition
becomes true
>= Greater than or If the value of left operand is greater than or (a >= b) is not true
Equal to equal to the value of right operand, then
the condition becomes true
<= less than or If the value of left operand is less than or (a <= b) is not true
Equal to equal to the value of right operand, then
the condition becomes true

Example:
>>> 1<2
True
>>> 3 > 34
False
>>> 23 == 45
3.4 Problem Solving and Python Programming

False
>>> 34 != 323
True

// operator gives the floor division result


>>> 4.0 // 3
1.0
>>> 4.0 / 3
1.3333333333333333

(iii) Assignment Operators


It is used to hold a value of evaluated expression and used for assigning the value of right
operand to the left operand. The following table shows assignment operators.
Example
Operation Description
(a=10, b=20)
= Assigns values from right side operands c = a + b assigns value of a + b into c
to left side operand
+= Add It adds right operand to the left operand c += a is equivalent to c = c + a
and assign the result to left operand
-= Sub It subtracts right operand from the left c -= a is equivalent to c= c - a
operand and assign the result to left
operand
*= Multiply It multiplies right operand with the left c *= a is equivalent to c= c * a
operand and assign the result to left
operand
/= Divide It divides left operand with the right c /= a is equivalent to c = c / a and c /= a
operand and assign the result to left is equivalent to c = c / a
operand
%= Modulus It takes modulus using two operands c %= a is equivalent to c= c% a
and assign the result to left operand
**=
Exponent Performs exponential (power) c **= a is equivalent to c= c **a
calculation on operators and assign
value to the left operand
//= Floor It performs floor division on operators c //= a is equivalent to c= c //a
Division and assign value to the left operand

(iv) Logical Operators


Python logical operators are used to combine two or more conditions and perform the logical
operations using Logical AND, Logical OR and Logically NOT. Below table describes them.
Control Flow 3.5

Operation Meaning Description Example


and Logical AND If both the operands are true then (a and b) is true.
condition becomes true.
or Logical OR If any of the two operands are non- (a or b) is true.
zero then condition becomes true.
not Logical NOT Used to reverse the logical state of Not (a and b) is
its operand false.

(v) Bitwise Operators


It works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in
binary format they will be as follows:

Example:
a = 0011 1100
b = 0000 1101
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Example
Operation Meaning Description
(a=10, b=20)
& Binary AND Operator copies a bit to the result (a & b) = 12
if it exists in both operands (means 0000 1100)
| Binary OR It copies a bit if it exists in either (a | b) = 61
operand. (means 0011 1101)
^ Binary XOR It copies the bit if it is set in one (a ^ b) = 49
operand but not both. (means 0011 0001)
~ Binary Ones It is unary and has the effect of (~a ) = -61
Complement ‘flipping’ bits. (means 1100 0011 in 2’s
complement form due to
a signed binary number.
<< Binary Left Shift The left operand value is moved a << = 240
left by the number of bits (means 1111 0000)
specified by the right operand.
>> Binary Right Shift The left operand value is moved a >> = 15
right by the number of bits (means 0000 1111)
specified by the right operand.

(vi) Membership Operators


Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below.
3.6 Problem Solving and Python Programming

Operation Description Example


in Evaluates to true if it finds a x in y, here in results in a 1 if x is a member
variable in the specified sequence and of sequence y.
false otherwise.
not in Evaluates to true if it does not finds a x not in y, here not in results in a 1 if x is
variable in the specified sequence and not a member of sequence y.
false otherwise.

(vii) Identity Operators


Identity operators compare the memory locations of two objects.There are two Identity
operators explained below

Description Example
is Evaluates to true if the variables on either x is y, here is results in 1 if id(x) equals
side of the operator point to the same id(y).
object and false otherwise.
is not Evaluates to false if the variables on x not in y, here not in results in a 1 if x is
either side of the operator point to the not a member of sequence y.
same object and true otherwise. x is not
y, here is not results in 1 if id(x) is not
equal to id(y).

3.3 OPERATORS PRECEDENCE


When writing Python expressions, it’s usually best to indicate the order of operations by
using parentheses (brackets). If parentheses are not used in an expression, the computer will perform
the operations in an order determined by procedures rules.

The following table lists all operators from highest precedence to lowest.
Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus (method names for the last two are
+@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>><< Right and left bitwise shift
& Bitwise ‘AND’
^| Bitwise exclusive ‘OR’ and regular ‘OR’
<= <>>= Comparison operators
Equality operators
= %= /= //= Assignment operators
-= += *= **=
is not Identity operators
Control Flow 3.7

in not in Membership operators


not or and Logical operators

3.4 DECISION MAKING


The execution of the program taking action according to the conditions. This concept is also
known as Conditional statements or Branching statements.

This technique is some what different from normal program. The sequence of the control
flow may differ from normal logical code. Decision structures evaluate multiple expressions which
produce TRUE or FALSE as outcome. The programmer to determine which action to take and
which statements to execute if outcome is TRUE or FALSE otherwise.

Python programming language provides following types of decision making statements.


Click the following links to check their detail.
Types of Conditional statements
(i) if statements (conditional)
(ii) if-else statements (alternative)
(iii) if-elif-else (chained conditional)
(iv) Nested Conditional

3.4.1 i) If Statement
It is similar to that of other languages. The if statement contains a logical expression using
data which is compared and a decision is made based on the result of the comparison.
Syntax
if expression:
statement(s)

Flowchart

False
Test
expression

True

Statement(s)

Figure. 3.1 Operation of if statement


3.8 Problem Solving and Python Programming

Example:
a=10
if a>9:
print(“A is Greater than 9”)

Output
A is Greater than 9

3.4.2 (ii) If... else Statement


An else statement can be combined with an if statement. An else statement contains the
block of code (false block) that executes if the conditional expression in the if statement resolves to
0 or a FALSE value.

The else statement is an optional statement and there could be at most only one else statement
following if.

Syntax
if expression:
statement(s)
else:
statement(s)

Flowchart

If Test False
expression

True

Body of if Body of Else

Figure. 3.2 Operation of if..else statement

Example 1:
a=10
b=20
if a>b:
Control Flow 3.9

print(“A is Greater than B”)


else:
print(“B is Greater than A”)

Output
B is Greater than A

Example 2:
num=3
#num= -5
#num=0
If num>=0:
Print(“Positive or Zero”)
else:
Print(“Negative number”)

Output
Positive or Zero
In the above example. When num is equal to 3, the test expression is true and body of if is
executed and body of else is skipped.

If num is equal to -5, the test expression is false and body of else is executed and body of if
is skipped.

When num is equal to 0, the test expression is true and body of if is executed and body of
else is skipped.

3.4.3 (iii) If...elif…else Statement


The elif statement allows you to check multiple expressions for TRUE and execute a block
of code as soon as one of the conditions evaluates to TRUE. Similar to the else, the elif statement is
optional. However, unlike else, for which there can be at most one statement, there can be an arbi-
trary number of elif statements following an if.

Syntax
if test expression:
statement(s)
elif test expression:
statement(s)
else:
statement(s)
Core Python does not provide switch or case statements as in other languages, but we can
use if..elif...statements to simulate switch case as follows:
3.10 Problem Solving and Python Programming

Flowchart

If Test False
expression

True
Elif Test False
Body of if expression

True
True

Body of elif Body of Else

Figure. 3.3 Operation of if..elif…else statement

Example 1
#num = 0
num = -3
#num = 4.5
if num > 0:
print(“Positive number”)
elif num == 0:
print(“Zero”)
else:
print(“Negative number”)
Output
Negative number

3.4.4 (iv) Nested Conditionals


One conditional can also be nested within another. (It is the same theme of composibility,
again!) We could have written the previous example as follows:

Syntax
if expression1:
statement(s)
else:
if expression2:
statement(s)
else:
statement(s)
Control Flow 3.11

Flowchart

False Test True


Condition 1

True Test False


Condition 2

Statement 3 Statement 1 Statement 2

Statement n

The outer conditional contains two branches. The second branch contains another if
statement, which has two branches of its own. Those two branches could contain conditional
statements as well.

Example
num = float(input(“Enter a number: “))
if num >= 0:
if num == 0:
print(“Zero”)
else:
print(“Positive number”)
else:
print(“Negative number”)

Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero
3.12 Problem Solving and Python Programming

3.5 ITERATION
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on. There may be a situation when you need to execute a block
of code several number of times.

A loop statement allows us to execute a statement or group of statements multiple times.


Repeated execution of a set of statements is called iteration. Programming languages provide
various control structures that allow more complicated execution paths. Python has two statements
for iteration and additional one technique for nested.

Types
(i) while loop
(ii) for loop
(iii) nested loop

(i) While Loop


A while loop statement executes a block of statement again and again until the condition
occurs false (or) Repeats a statement or group of statements while a given condition is TRUE.

It tests the condition before executing the loop body so this technique is known as Entry
controlled loop.

Syntax
while expression:
statement(s)

Here, statement(s) may be a single statement or a block of statements.

The condition may be any expression, and true is any non-zero value. The loop iterates
while the condition is true. When the condition becomes false, program control passes to the line
immediately following the loop.

Flowchart
Enter while loop

Test False
expression

True

Body of while Exit loop


Control Flow 3.13

Example
count = 0
while (count < 9):
print( ‘The count is:’, count)
count = count + 1
print (“Good bye!”)

Output
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

(ii) For Loop


Executes a sequence of statements multiple times and abbreviates the code that manages the
loop variable.

Syntax
for iterating_var in sequence:
statements(s)

If a sequence contains an expression list, it is evaluated first. Then, the first item in the
sequence is assigned to the iterating variable iterating_var. Next, the statements block is executed.
Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the
entire sequence is exhausted.

Flowchart
for each item in sequence

Test No
expression

Yes

Body of for Exit loop


3.14 Problem Solving and Python Programming

Example
numbers=[6,5,3,8,4,2,5,4,11]
sum=0
for val in numbers:
sum=sum+val
print(“ The sum is”, sum)

Output
The sum is 48

(iii) Break
It terminates the current loop and resumes execution at the next statement, just like the
traditional break statement in C.

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

Syntax
break

Flowchart

Example:
for val in "string":
if val == "i":
break
print(val)
print("The end")
Control Flow 3.15

Output
s
t
r
The end
In this program, it iterates through the "string" sequence.and check if the letter is "i", upon
which we break from the loop. Hence, we see in our output that all the letters until "i" gets printed.
After that, the loop terminates.

Continue:
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.

Syntax
continue

Flowchart

The working of continue statement in for and while loop is shown below.
3.16 Problem Solving and Python Programming

Example:
for val in "string":
if val == "i":
continue
print(val)
print("The end")
Output
s
t
r
n
g
The end
This program is same as the above example except the break statement has been replaced
with continue.

We continue with the loop, if the string is "i", not executing the rest of the block. Hence, we
see in our output that all the letters except "i" gets printed.

Pass Statement
In Python programming, pass is a null statement. The difference between a comment and
pass statement in Python is that, while the interpreter ignores a comment entirely, pass is not ignored

The pass statement is a null operation; nothing happens when it executes.

Syntax
pass

Example:
for letter in ‘Python’:
if letter == ‘h’:
pass
Control Flow 3.17

print (‘This is pass block’)


print (‘Current Letter :’, letter)
print (“Good bye!”)

Output
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
Number data types store numeric values. They are immutable data types, means that
changing the value of a number data type results in a newly allocated object. Number objects are
created when you assign a value to them.

3.6 FRUITFUL FUNCTIONS


A fruitful function is a function that returns a value when it is called. Most of the builtin
functions that we have used are fruitful.

For example, the function abs returns a new number – namely, the absolute value of its
argument:
>>> abs(−42)
42
Some functions are not fruitful. For example, suppose franklin refers to a Turtle object, the
function call franklin.forward(100) does not return anything. Instead it causes franklin to move
forward. In addition, all of the functions defined in the previous handout are not fruitful.

Defining a fruitful function


If we want a function to return a result to the caller of the function, we use the return
statement. For example, here we define two fruitful functions. The second one, circle area, calls the
first one, square, to square the radius.

import math
def square(x):
return x * x
def circle area (diameter ):
radius = diameter / 2.0
return math.pi * square(radius)
3.18 Problem Solving and Python Programming

In general, a return statement consists of the return keyword followed by an expression,


which is evaluated and returned to the function caller.

How python evaluates a return statement? Python evaluates fruitful functions pretty much
the same way as non-fruitful ones
(1) Evaluates the expression to produce a data value.
(2) Passes that data value back to the caller.
(3) Leaves the function immediately and returns to the location where the function was
called.
Python returns immediately when it reaches a return statement. The print statement in the
function body below will never be executed

def square(x):
return x * x # pytho n leaves function here . ..
print ("I am NEVER printed!") # . . . and never gets to here .

Return vs Print Function


The return statement sends a data value back to the caller of the function; the print statement
displays a data value on the screen. You will need to use both.

Here’s a general rule of thumb:


Use return to share the result with another part of your program; use print to share the result
with the user.

The square function must use a return statement because it is called inside the circle area
function. In other words, the point of this function is to share the result (i.e., the squared number)
with another part of our program (i.e., the circle area function).

Parameters
A callable object is an object that can accept some arguments (also called parameters) and
possibly return an object (often a tuple containing multiple objects). A function is the simplest
callable object in Python, but there are others, such as classes or certain class instances.

•• formal parameter — the identifier used in a method to stand for the value that is passed
into the method by a caller.
◦◦ For example, amount is a formal parameter of processDeposit
•• actual parameter — the actual value that is passed into the method by a caller.
◦◦ For example, the 200 used when processDeposit is called is an actual parameter.
◦◦ actual parameters are often called arguments
Control Flow 3.19

Example:
x in:
def cube(x):
return x*x*x
Pass-by-value parameter passing-- the value of the actual parameter is copied to the formal
parameter. With pass-by-value, there is no way for the actual parameter to change value as the
function gets its own copy.

In Python, scalar values are sent by-value. Lists and other objects are sent by reference.

Instructor Demo: Trace the following:


def processNumber(x):
x=72
return x+3
# main
y=54
res = processNumber(y)
Pass-by-Reference parameter passing-- a reference to the actual parameter is sent to the
function. When we trace a program, and a list is sent, we don’t copy the list to the actual parameter
box, we draw an arrow from formal to actual.

Instructor Demo: Trace the following:


def processList(list):
list[1]=99
# main
aList = [5,2,9]
processList(aList)

3.7 SCOPE OF THE VARIABLE


Variable scope and lifetime
A variable which is defined in the main body of a file is called a global variable. It will be
visible throughout the file, and also inside any file which imports that file. Global variables can
have unintended consequences because of their wide-ranging effects – that is why we should almost
never use them. Only objects which are intended to be used globally, like functions and classes,
should be put in the global name space.

A variable which is defined inside a function is local to that function. It is accessible from
the point at which it is defined until the end of the function, and exists for as long as the function
is executing. The parameter names in the function definition behave like local variables, but they
contain the values that we pass into the function when we call it. When we use the assignment
operator(=)inside a function, its default behavior is to create a new local variable – unless a variable
with the same name is already defined in the local scope.
3.20 Problem Solving and Python Programming

Variables in different scopes:


# This is a global variable a = 0
if a == 0:

# This is still a global variable b = 1


def my_function(c):
# this is a local variable d = 3
print(c)
print(d)

#Now we call the function, passing the value 7 as the first and only parameter
my_function(7)
# a and b still
exist print(a)
print(b)
# c and d don’t exist anymore -- these statements will give us name errors!

print(c)
print(d)

3.7.1 Global and local Variables in Functions


In the following example, it is demonstrated, how global values can be used inside the body
of a function:
def f():
print(s)
s = “I love India!”
f()
The variable s is defined as the string “I love Paris in the summer!”, before calling the
function f(). The body of f() consists solely of the “print(s)” statement. As there is no local variable
s, i.e. no assignment to s, the value from the global variable s will be used. So the output will be the
string.

“I love Paris in the summer!”. The question is, what will happen, if we change the value of
s inside of the function f()? Will it affect the global variable as well? We test this in the following
piece of code:

Example:
def f():
s = “I love India!”
Control Flow 3.21

print(s)
s = “I love Tamilnadu!”
f()
print(s)
Output
I love India!
I love Tamilnadu!
What if we combine the first example with the second one, i.e. first access s with a print()
function, hoping to get the global value, and then assigning a new value to it? Assigning a value to
it, would mean creating a local variable s. So, we would have s both as a global and a local variable
in the same scope, i.e. the body of the function. Python doesn’t allow this ambiguity. So, it will
throw an error, as we can see in the following example:

>>> def f():


print(s)
s = “I love London!”
print(s)
>>> s = “I love Paris!”
>>> f()
A variable can’t be both local and global inside of a function. So Python decides that we
want a local variable due to the assignment to s inside of f(), so the first print statement before the
definition of s throws the error message above. Any variable which is changed or created inside of
a function is local, if it hasn’t been declared as a global variable. To tell Python, that we want to use
the global variable, we have to explicitly state this by using the keyword “global”, as can be seen in
the following example:

def f():
global s
print(s)
s = “God is great!”
print(s)
s = “I am looking for a course in Engineering!”
f()
print(s)
We have solved our problem. There is no ambiguity left. The output of this small script
looks like this:

I am looking for a course in Engineering!


3.22 Problem Solving and Python Programming

God is great!

God is great!

Local variables of functions can’t be accessed from outside, when the function call has
finished:
def f():
s = “I am globally not known”
print(s)
f()
print(s)
The following example shows a wild combination of local and global variables and function
parameters:
def foo(x, y):
global a
a = 42
x,y = y,x
b = 33
b = 17
c = 100
print(a,b,x,y)
a,b,x,y = 1,15,3,4
foo(17,4)
print(a,b,x,y)

Output:
42 17 4 17
42 15 3 4

3.7.2 Nonlocal Variables


Python3 introduced nonlocal variables as a new kind of variables. Nonlocal variables have
a lot in common with global variables. One difference to global variables lies in the fact that it is not
possible to change variables from the module scope, i.e. variables which are not defined inside of a
function, by using the nonlocal statement.
def f():
global x)
print(x)
Control Flow 3.23

x=3
f()
This program is correct and returns the number 3 as the output.

We will change “global” to “nonlocal” in the following program:


def f():
nonlocal x
print(x)
x=3
f()
The program, which we have saved as example1.py, cannot be executed anymore now. We
get the following error:
File “example1.py”, line 2
nonlocal x
SyntaxError: no binding for nonlocal ‘x’ found

3.8 COMPOSITION
As you should expect by now, you can call one function from within another. This ability is
called composition.

As an example, we’ll write a function that takes two points, the center of the circle and a
point on the perimeter, and computes the area of the circle.

Assume that the center point is stored in the variables xc and yc, and the perimeter point is
in xp and yp. The first step is to find the radius of the circle, which is the distance between the two
points. Fortunately, we’ve just written a function, distance, that does just that, so now all we have
to do is use it:
radius = distance (xc, yc, xp, yp)

The second step is to find the area of a circle with that radius and return it. Again we will
use one of our earlier functions:

result = area(radius)
return result
Wrapping that up in a function, we get:
def area2(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
3.24 Problem Solving and Python Programming

We called this function area 2 to distinguish it from the area function defined earlier.

The temporary variables radius and result are useful for development, debugging, and
single-stepping through the code to inspect what is happening, but once the program is working, we
can make it more concise by composing the function calls:
def area2(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))

Boolean functions
Functions can return booleans, which is often convenient for hiding complicated tests inside
functions.

Example:
def is_divisible(x, y):
if x % y == 0:
return True
else:
return False
It is common to give boolean functions names that sound like yes/ no questions; is_divisible
returns either True or False to indicate whether x is divisible by y.

Example:
>>> is_divisible(6, 4)
False
>>> is_divisible(6, 3)
True
The result of the == operator is a boolean, so we can write the function more concisely by
returning it directly:
def is_divisible(x, y):
return x % y == 0
Boolean functions are often used in conditional statements:
if is_divisible(x, y):
print ‘x is divisible by y’

It might be tempting to write something like:


if is_divisible(x, y) == True:
print ‘x is divisible by y’
Control Flow 3.25

But the extra comparison is unnecessary.

It is common to give boolean functions names that sound like yes/ no questions; is_divisible
returns either True or False to indicate whether x is divisible by y.

3.9 RECURSION
A recursive definition is similar to a circular definition, in the sense that the definition
contains a reference to the thing being defined.

If you looked up the definition of the factorial function, denoted with the symbol !, you
might get something like this:
0! = 1
n! = n (n−1)!

This definition says that the factorial of 0 is 1, and the factorial of any other value, n, is n
multiplied by the factorial of n−1.

So 3! is 3 times 2!, which is 2 times 1!, which is 1 times 0!. Putting it all together, 3! equals
3 times 2 times 1 times 1, which is 6.

If you can write a recursive definition of something, you can usually write a Python program
to evaluate it. The first step is to decide what the parameters should be. In this case it should be clear
that factorial takes an integer:

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

Otherwise, and this is the interesting part, we have to make a recursive call to find the
factorial of n−1 and then multiply it by n:
def factorial(n):
if n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
return result
3.26 Problem Solving and Python Programming

Explanation
If we call factorial with the value 3:
Since 3 is not 0, we take the second branch and calculate the factorial of n-1...
Since 2 is not 0, we take the second branch and calculate the factorial of n-1...
Since 1 is not 0, we take the second branch and calculate the factorial of n-1...
Since 0 is 0, we take the first branch and return 1 without making any more recursive
calls.
The return value (1) is multiplied by n, which is 1, and the result is returned.
The return value (1) is multiplied by n, which is 2, and the result is returned.
The return value (2) is multiplied by n, which is 3, and the result, 6, becomes the return
value of the function call that started the whole process.
Here is what the stack diagram looks like for this sequence of function calls:

Stack Diagram
The return values are shown being passed back up the stack. In each frame, the return value
is the value of result, which is the product of n and recurse.

In the last frame, the local variables recurse and result do not exist, because the branch that
creates them does not execute.

3.10 STRINGS
Strings are amongst the most popular types in Python. We can create them simply by
enclosing characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable.
For example −
var1 ='Hello World!'
var2 ="Python Programming"
Accessing Values in Strings

Python does not support a character type; these are treated as strings of length one, thus also
considered a substring.
Control Flow 3.27

To access substrings, use the square brackets for slicing along with the index or indices to
obtain your substring. For example −
var1 = 'Hello World!'
var2 = "Python Programming"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])
When the above code is executed, it produces the following result −
var1[0]: H
var2[1:5]: ytho

Updating Strings
You can "update" an existing string by (re)assigning a variable to another string. The new
value can be related to its previous value or to a completely different string altogether. For example
var1 = 'Hello World!'
print ("Updated String :- ", var1[:6] + 'Python')
When the above code is executed, it produces the following result −
Updated String :- Hello Python

Escape Characters
Following table is a list of escape or non-printable characters that can be represented with
backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
Backslash notation Hexadecimal character Description
\a 0x07 Bell or alert
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\nnn Octal notation, where n is in the range 0.7
\r 0x0d Carriage return
\s 0x20 Space
\t 0x09 Tab
\v 0x0b Vertical tab
\x Character x
3.28 Problem Solving and Python Programming

\xnn Hexadecimal notation, where n is in the range 0.9,


a.f, or A.F

String Special Operators


Assume string variable a holds 'Hello' and variable b holds 'Python', then −
Operator Description Example
+ Concatenation - Adds values on either side of the a + b will give HelloPython
operator
* Repetition - Creates new strings, concatenating a*2 will give -HelloHello
multiple copies of the same string
[] Slice - Gives the character from the given index a[1] will give e
[:] Range Slice - Gives the characters from the given a[1:4] will give ell
range
in Membership - Returns true if a character exists in H in a will give 1
the given string
not in Membership - Returns true if a character does not M not in a will give 1
exist in the given string
r/R Raw String - Suppresses actual meaning of Escape print r'\n' prints \n and print
characters. The syntax for raw strings is exactly R'\n'prints \n
the same as for normal strings with the exception
of the raw string operator, the letter "r," which
precedes the quotation marks. The "r" can be
lowercase (r) or uppercase (R) and must be placed
immediately preceding the first quote mark.

String special operators


Assume string variable a holds ‘Hello’ and variable b holds ‘Python’,

String formatting operator


One of Python’s coolest features is the string format operator %. This operator is unique to
strings and makes up for the pack of having functions from C’s printf() family.

Example
print “My name is %s and weight is %d kg!” % (‘Zara’, 21)

Output
My name is Zara and weight is 21 kg!
Here is the list of complete set of symbols which can be used along with % −
Control Flow 3.29

Format Symbol Conversion


%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase ‘e’)
%E exponential notation (with UPPERcase ‘E’)
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E

Triple Quotes
Python’s triple quotes comes to the rescue by allowing strings to span multiple lines,
including verbatim NEWLINEs, TABs, and any other special characters.

The syntax for triple quotes consists of three consecutive single ordouble quotes.
para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print (para_str)
When the above code is executed, it produces the following result. Note how every single
special character has been converted to its printed form, right down to the last NEWLINE at the end
of the string between the "up." and closing triple quotes. Also note that NEWLINEs occur either
with an explicit carriage return at the end of a line or its escape code (\n) −

This is a long string that is made up of several lines and non-printable characters such as:

TAB ( ) and they will show up that way when displayed. NEWLINEs within the string,
whether explicitly given like this within the brackets [], or just a NEWLINE within the variable
assignment will also show up.

Raw strings do not treat the backslash as a special character at all. Every character you put
into a raw string stays the way you wrote it
3.30 Problem Solving and Python Programming

print ‘C:\\nowhere’
Output
C:\nowhere
Now let’s make use of raw string. We would put expression inr ’expression’ as follows −
print r’
C:\\nowhere’
Output
C:\\nowhere

3.11 STRING SLICES


The “slice” syntax is a handy way to refer to sub-parts of sequences typically strings and
lists. The slice s[start:end] is the elements begin-ning at start and extending up to but not including
end. Suppose we have s = “Hello”.
s[1:4] is ‘ell’ – chars starting at index 1 and extending up to butnot including index 4
s[1:] is ‘ello’ – omitting either index defaults to the start or end ofthe string
s[:] is ‘Hello’ – omitting both always gives us a copy of the wholething (this is the
pythonic way to copy a sequence like a string or list)
s[1:100] is ‘ello’ – an index that is too big is truncated down to thestring length

The standard zero-based index numbers give easy access to chars near the start of the string.
As an alternative, Python uses negative numbers to give easy access to the chars at the end of the
string: s[-1] is the last char ‘o’, s[-2] is ‘l’ the next-to-last char, and so on. Negative index numbers
count back from the end of the string:
s[-1] is ‘o’ – last char (1st from the end)
s[-4] is ‘e’ – 4th from the end
s[:-3] is ‘He’ – going up to but not including the last 3 chars.
s[-3:] is ‘llo’ – starting with the 3rd char from the end and extending to the end of the
string.
It is a neat truism of slices that for any index n, s[:n] + s[n:] == s. This works even for n
negative or out of bounds. Or put another way s[:n] and s[n:] always partition the string into two
string parts, conserving all the characters. As we’ll see in the list section later, slices work with lists
too.

3.12 STRING ARE IMMUTABLE


One final thing that makes strings different from some other Python collection types is that
you are not allowed to modify the individual characters in the collection. It is tempting to use the []
operator on the left side of an assignment, with the intention of changing a character in a string. For
example, in the following code, we would like to change the first letter of greeting.
Control Flow 3.31

greeting = “Hello, world!”


greeting[0] = ‘J’ # ERROR!
print(greeting)
Instead of producing the output Jello, world!, this code produces the runtime error TypeError:
‘str’ object does not support item assignment.

Strings are immutable, which means you cannot change an existing string. The best you can
do is create a new string that is a variation on the original.
reeting = “Hello, world!”
newGreeting = ‘J’ + greeting[1:]
print(newGreeting)
print(greeting)
Output
Jello, world!
Hello, world!
The solution here is to concatenate a new first letter onto a slice of greeting. This operation
has no effect on the original string.

3.13 STRING FUNCTIONS AND METHODS


Python includes the following built-in methods to manipulate strings
Method Description
Python String capitalize() Converts first character to Capital Letter
Python String center() Pads string with specified character
Python String casefold() converts to casefolded strings
Python String count() returns occurrences of substring in string
Python String endswith() Checks if String Ends with the Specified Suffix
Python String expandtabs() Replaces Tab character With Spaces
Python String encode() returns encoded string of given string
Python String find() Returns the Lowest Index of Substring
Python String format() formats string into nicer output
Python String index() Returns Index of Substring
Python String isalnum() Checks Alphanumeric Character
Python String isalpha() Checks if All Characters are Alphabets
Python String isdecimal() Checks Decimal Characters
Python String isdigit() Checks Digit Characters
Python String isidentifier() Checks for Valid Identifier
Python String islower() Checks if all Alphabets in a String are Lowercase
3.32 Problem Solving and Python Programming

Method Description
Python String isnumeric() Checks Numeric Characters
Python String isprintable() Checks Printable Character
Python String isspace() Checks Whitespace Characters
Python String istitle() Checks for Titlecased String
Python String isupper() returns if all characters are uppercase characters
Python String join() Returns a Concatenated String
Python String ljust() returns left-justified string of given width
Python String rjust() returns right-justified string of given width
Python String lower() returns lowercased string
Python String upper() returns uppercased string
Python String swapcase() swap uppercase characters to lowercase; vice versa
Python String lstrip() Removes Leading Characters
Python String rstrip() Removes Trailing Characters
Python String capitalize() Converts first character to Capital Letter
Python String center() Pads string with specified character
Python String casefold() converts to casefolded strings
Python String count() returns occurrences of substring in string
Python String endswith() Checks if String Ends with the Specified Suffix
Python String expandtabs() Replaces Tab character With Spaces
Python String encode() returns encoded string of given string
Python String find() Returns the Lowest Index of Substring
Python String format() formats string into nicer output
Python String index() Returns Index of Substring
Python String isalnum() Checks Alphanumeric Character
Python String isalpha() Checks if All Characters are Alphabets
Python String isdecimal() Checks Decimal Characters
Python String isdigit() Checks Digit Characters
Python String isidentifier() Checks for Valid Identifier
Python String islower() Checks if all Alphabets in a String are Lowercase
Python String isnumeric() Checks Numeric Characters
Python String isprintable() Checks Printable Character
Python String isspace() Checks Whitespace Characters
Python String istitle() Checks for Titlecased String
Python String isupper() returns if all characters are uppercase characters
Python String join() Returns a Concatenated String
Python String ljust() returns left-justified string of given width
Python String rjust() returns right-justified string of given width
Control Flow 3.33

Method Description
Python String lower() returns lowercased string
Python String upper() returns uppercased string
Python String swapcase() swap uppercase characters to lowercase; vice versa
Python String lstrip() Removes Leading Characters
Python String rstrip() Removes Trailing Characters
Python String capitalize() Converts first character to Capital Letter
Python String center() Pads string with specified character
Python String casefold() converts to casefolded strings
Python String count() returns occurrences of substring in string
Python String endswith() Checks if String Ends with the Specified Suffix
Python String expandtabs() Replaces Tab character With Spaces
Python String encode() returns encoded string of given string
Python String find() Returns the Lowest Index of Substring
Python String format() formats string into nicer output
Python String index() Returns Index of Substring
Python String isalnum() Checks Alphanumeric Character

3.14 STRING MODULE


This module contains a number of functions to process standard Python strings. In recent
versions, most functions are available as string methods as well.

Example :
import string
text = “Monty Python’s Flying Circus”
print “upper”, “=>”, string.upper(text)
print “lower”, “=>”, string.lower(text)
print “split”, “=>”, string.split(text)
print “join”, “=>”, string.join(string.split(text), “+”)
print “replace”, “=>”, string.replace(text, “Python”, “Java”)
print “find”, “=>”, string.find(text, “Python”), string.find(text, “Java”)
print “count”, “=>”, string.count(text, “n”)

Output
upper => MONTY PYTHON’S FLYING CIRCUS lower => montypython’s flying
circus
split => [‘Monty’, “Python’s”, ‘Flying’, ‘Circus’] join => Monty+Python’s+Flying+Circus
replace => Monty Java’s FlyingCircus
find => 6 -1
count => 3
3.34 Problem Solving and Python Programming

3.15 LISTS AS ARRAY


One of the most fundamental data structures in any language is the array. Python doesn’t
have a native array data structure, but it has the list which is much more general and can be used as
a multidimensional array quite easily.

List basics
A list in Python is just an ordered collection of items which can be of any type. By comparison
an array is an ordered collection of items of a single type - so in principle a list is more flexible
than an array but it is this flexibility that makes things slightly harder when you want to work with
a regular structure.

A list is also a dynamic mutable type and this means you can add and delete elements from
the list at any time.

To define a list you simply write a comma separated list of items in square brackets:

myList=[1,2,3,4,5,6]

This looks like an array because you can use “slicing” notation to pick out an individual
element - indexes start from 0.

Example:
print myList[2]
will display the third element, i.e. the value 3 in this case. Similarly to change the third
element you can assign directly to it:
myList[2]=100
The slicing notation looks like array indexing but it is a lot more flexible.

Example:
myList[2:5]
is a sublist from the third element to the fifth i.e. from myList[2] to myList[4].
Notice that the final element specified i.e. [5] is not included in the slice.
Also notice that you can leave out either of the start and end indexes and they will be
assumed to have their maximum possible value.

Example:
myList[5:]
is the list from List[5] to the end of the list and
myList[:5]
is the list up to and not including myList[5] and
Control Flow 3.35

myList[:]
is the entire list.
List slicing is more or less the same as string slicing except that you can modify a slice.

Example:
myList[0:2]=[0,1]
has the same effect as
myList[0]=0
myList[1]=1
Finally is it worth knowing that the list you assign to a slice doesn’t have to be the same size
as the slice - it simply replaces it even if it is a different size.

ILLUSTRATIVE PROGRAMS :
Square Root :
import math
a=float(input("Enter a value"))
print("The exponential value of {0} is ".format(a),math.exp(a))

Output:
Enter 'x' for exit.
Enter a number: 3
Square Root of 3.000 is 1.732
Enter 'x' for exit.
Enter a number: 16
Square Root of 16.000 is 4.000
Enter 'x' for exit.
Enter a number: x

Greatest Common Divisor:


a=int(input("x value="))
b=int(input("y value="))
gcd(a,b)
def gcd(x, y):
gcd = 1
if x % y == 0:
3.36 Problem Solving and Python Programming

return y
for k in range(int(y / 2), 0, -1):
if x % k == 0 and y % k == 0:
gcd = k
break
print("The Greatest Common Divisor of {0} and {1} is".format(x,y),gcd)
#gcd(a,b)

Output
x value=90
y value=100
The Greatest Common Divisor of 90 and 100 is 10

BinarySearch:
def binarySearch(myItem,myList):
found = False
bottom = 0
top = len(myList) - 1
while bottom <= top and not found:
middle = (bottom+top)//2
if myList[middle] == myItem:
found = True
elif myList[middle] < myItem:
bottom = middle + 1
else:
top = middle-1
return found
if __name__=="__main__":
#numberList=[1,3,4,8,69,45,32,46,78,20,25,46,10,75,36,99,100]
numberList = []
while True:
print("Enter '-1' for exit.")
list1=int(input("Enter numbers: "))
Control Flow 3.37

if list1 == -1:
break
else:
numberList.append(list1)
print("The created number list is \n",numberList)
number = int(input("Enter your number to search: "))
isitFound = binarySearch(number,numberList)
if isitFound:
print("The entered number {0} is in the list".format(number))
else:
print("The entered number {0} is not in the list".format(number))

Output
Enter your number to search: 45
The entered number 45 is in the list
Enter your number to search: 1000
The entered number 1000 is not in the list

Linear Search :
def linearSearch(myItem,myList):
found = False
position = 0
while position < len(myList) and not found:
if myList[position] == myItem:
found = True
position = position +1
return found

if __name__=="__main__":
shopping = []
while True:
print("Enter 'x' for exit.")
list1=input("Enter items: ")
3.38 Problem Solving and Python Programming

if list1 == 'x':
break
else:
shopping.append(list1)
print("The created list is \n",shopping)

#shopping=["Apple","Banana","Orange","Guvava","Pienapple","Bread","Milk"]
item = input("Enter your item to search: ")
isitFound = linearSearch(item,shopping)
if isitFound:
print("Your item is in the list")
else:
print("Sorry your item not in the list")
Output
Enter your item to search: Apple
Your item is in the list
Enter your item to search: Butter
Sorry your item not in the list
UNIT – 4

COMPOUND DATA:
LISTS, TUPLES, DICTIONARIES

4.1 LISTS
A list is a sequence of any type of values and can be created as a set of comma-separated
values within square brackets. The values in a list are called elements or items. A list within another
list is called nested list.

Sample code for creating lists


list1 = [‘Ram’, ‘Chennai’, 2017] # list of different types of elements
list2 = [10, 20, 30, 40, 50] # list of numbers
list3 = [] # empty list
list4 = [‘Priya’, 2017, 99.8, [‘Mumbai’, ‘India’]] # nested list
print list1
print list2, list3
print list4

Sample Output:
[‘Ram’, ‘Chennai’, 2017]
[10, 20, 30, 40, 50] [ ]
[‘Priya’, 2017, 99.8, [‘Mumbai’, ‘India’]]

4.1.1 Accessing elements in lists using subscript operator


The indices of list’s elements are numbered from 0 from the left end and numbered from -1
from the right end. For a list [‘Ram’, ‘Chennai’, 2017], the indices of elements ‘Ram’, ‘Chennai’
and 2017 are shown in the following figure:
Element ‘Ram’ ‘Chennai’ 2017
Index from left end 0 1 2
Index from right end –3 –2 –1
To access the element(s) of a list, subscript operator [ ] (also known as slicing operator) is
used. Index within [ ] indicates the position of the particular element in the list and it must be an
integer expression.
4.2 Problem Solving and Python Programming

For eg, in a list stulist = [‘Ram’, ‘Chennai’, 2017], stulist[1] returns Chennai as its output.

4.1.2 List operations


Lists operate on + and * operators. Here, + represents concatenation and * represents
repetition. The following code explains the concatenation of two lists named num1 and num2:

Sample Code and output for + (Concatenation)


Code Output
num1=[10, 20, 30] [10, 20, 30]
num2=[40, 50] [40, 50]
num3=num1+num2 [10, 20, 30, 40, 50]
print num1
print num2
print num3

The following code is another example for concatenation, where a list contains elements of
different data types:
Code Output
stulist = [‘Ram’, ‘Chennai’, 2017] [‘Ram’, ‘Chennai’, 2017]
newlist = stulist+[‘CSE’] [‘Ram’, ‘Chennai’, 2017, ‘CSE’]
print stulist
print newlist

Sample code and output for * (Repetition)


The following code describes the repetition operation which is performed on a list num1 for
3 times:
Code Output
num1=[10, 20] [10, 20]
num2=num1*3 [10, 20, 10, 20, 10, 20]
print num1
print num2

4.1.3 List Slices


A part of a list is called list slice. The operator [m:n] returns the part of the list from mth
index to nth index, including the element at mth index but excluding the element at nth index.

If the first index is omitted, the slice starts at the beginning of the string. If the second index
is omitted, the slice goes to the end of the string. If the first index is greater than or equals to the
second, the slice is an empty string. If both indices are omitted, the slice is a given string itself.
Compound Data: Lists, Tuples, Dictionaries 4.3

Sample code and output for list slicing


Code Output Description
stulist = [‘Ram’, List is created with 3 elements
‘Chennai’, 2017]
print stulist[0] Ram Slice has the element at index 0
print stulist[:3] [‘Ram’, ‘Chennai’, 2017] Slice is from the beginning
print stulist[1:] [‘Chennai’, 2017] Slice goes to the end
print stulist[1:1] [] Slice is empty
print stulist[5:2] [] Slice is empty
print stulist[:] [‘Ram’, ‘Chennai’, 2017] Entire list is the slice
print stulist[-2:] [‘Chennai’, 2017] Slice goes to the end
print stulist[:-2] [‘Ram’] Slice is from the beginning
print stulist[1:3] [‘Chennai’, 2017] Slice is from 1st index to 2nd index
(excluding the 3rd index)

4.1.4 List methods


Python provides the following methods that works on lists:

1. append
Adds element to the end of specified list and does not return any value.

Syntax: listname.append(element)

Sample code for append


stulist = [‘Ram’, ‘Chennai’, 2017]
stulist.append(‘CSE’)
print ‘After appending’
print stulist

Sample output:
After appending
[‘Ram’, ‘Chennai’, 2017, ‘CSE’]

2. count
Returns the number of occurrences of an element in a specified list.

Syntax: listname.count(element)

Sample code for count


stulist = [‘Ram’, ‘Chennai’, 2017, ‘Priya’, ‘Mumbai’, 2017]
4.4 Problem Solving and Python Programming

print stulist
print ‘Count for Chennai : ‘, stulist.count(‘Chennai’)
print ‘Count for 2017 : ‘, stulist.count(2017)
Sample output:
[‘Ram’, ‘Chennai’, 2017, ‘Priya’, ‘Mumbai’, 2017]
Count for Chennai : 1
Count for 2017 : 2

3. extend
Appends the contents of secondlist to the firstlist and does not return any value.
Syntax: firstlist.extend(secondlist)

Sample code for extend


stulist = [‘Ram’, ‘Chennai’, 2017]
dept = [‘CSE’]
print “Before Extend : “, stulist
stulist.extend(dept)
print “After Extend : “, stulist

Sample output:
Before Extend : [‘Ram’, ‘Chennai’, 2017]
After Extend : [‘Ram’, ‘Chennai’, 2017, ‘CSE’]

4. index
Returns the index of an element, if an element is found in the specified list. Else, an exception
is raised.
Syntax: listname.index(element)

Sample code for index


stulist = [‘Ram’, ‘Chennai’, 2017]
print ‘Index of Ram : ‘, stulist.index( ‘Ram’ )
print ‘Index of Chennai : ‘, stulist.index( ‘Chennai’ )
print ‘Index of 2017 : ‘, stulist.index(2017)
Sample output:
Index of Ram : 0
Index of Chennai : 1
Index of 2017 : 2
Compound Data: Lists, Tuples, Dictionaries 4.5

6. insert
Inserts the given element at the given index in a specified list and does not return any value
Syntax: listname.insert(index, element)

Sample code for insert


stulist = [‘Ram’, ‘Chennai’, 2017]
print ‘Before insert : ‘,stulist
stulist.insert(1, ‘CSE’)
print ‘After insert : ‘, stulist

Sample output:
Before insert : [‘Ram’, ‘Chennai’, 2017]
After insert : [‘Ram’, ‘CSE’, ‘Chennai’, 2017]

7. pop
Removes and returns the element from the end of specified list
Syntax: listname.pop()

Sample code for pop


stulist = [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
print ‘Initial list is : ‘, stulist
print ‘Popping the last item : ‘, stulist.pop()
print ‘After popping the last item, the list is : ‘, stulist

Sample output:
Initial list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
Popping the last item : 92.7
After popping the last item, the list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’]

8. pop(index)
Removes and returns the element at given index.
Syntax: listname.pop(index)

Sample code for pop(index)


stulist = [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
print ‘Initial list is : ‘, stulist
print ‘Popping an item with index 2 : ‘, stulist.pop(2)
4.6 Problem Solving and Python Programming

# 2 is an index of the item to be removed


print ‘Now the list is : ‘,stulist
Sample output:
Initial list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
Popping an item with index 2 : 2017
Now the list is : [‘Ram’, ‘Chennai’, ‘CSE’, 92.7]

9. remove
Removes an element from the list and does not return any value.
Syntax: listname.remove(element)

Sample code for remove


stulist = [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7, 2017]
print ‘Initial list is : ‘, stulist
stulist.remove(‘CSE’)
print ‘After removing CSE from the list : ‘, stulist
stulist.remove(2017)
print ‘After removing 2017 from the list : ‘, stulist
Sample output:
Initial list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7, 2017]
After removing CSE from the list : [‘Ram’, ‘Chennai’, 2017, 92.7, 2017]
After removing 2017 from the list : [‘Ram’, ‘Chennai’, 92.7, 2017]

10. reverse
Reverses the entire list.
Syntax: listname.reverse()

Sample code for reverse


stulist = [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
print ‘Initial list is : ‘, stulist
stulist.reverse()
print ‘After reversing, the list is : ‘, stulist

Sample output:
Initial list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
After reversing, the list is : [92.7, ‘CSE’, 2017, ‘Chennai’, ‘Ram’]
Compound Data: Lists, Tuples, Dictionaries 4.7

11. sort
Sorts the list in ascending order.
Syntax: listname.sort()

Sample code for sort


numlist = [6, 28, 11, 4, 20, 26, 13, 12]
print ‘Before sorting : ‘, numlist
numlist.sort()
print ‘After sorting is : ‘, numlist

Sample output:
Before sorting : [6, 28, 11, 4, 20, 26, 13, 12]
After sorting is : [4, 6, 11, 12, 13, 20, 26, 28]

stulist = [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]


print ‘Initial list is : ‘, stulist
stulist.sort()
print ‘After sorting, the list is : ‘, stulist

Sample output:
Initial list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
After sorting, the list is : [92.7, 2017, ‘CSE’, ‘Chennai’, ‘Ram’]

4.1.5 List Loop


The general way to traverse the elements of a list is with for loop. The following code shows
the use of for loop in accessing the elements of a list.
numlist = [1, 2, 3, 4, 5]
for i in numlist:
print i
Output:
1
2
3
4
5
The following code illustrates the use of range and len functions in accessing the indices of
the elements of a list:
numlist = [1, 2, 3, 4, 5]
4.8 Problem Solving and Python Programming

for i in range(len(numlist)):
print i
Output:
0
1
2
3
4
Here, len is a function that returns the number of elements in the list and range is a function
that returns a list of indices from 0 to n − 1, where n is the length of the list. The following code
gives an idea to traverse the list and to update the elements of a list with the help of range and len
functions in for loop:

numlist = [1, 2, 3, 4, 5]
for i in range(len(numlist)):
numlist[i]=numlist[i]+10
for i in numlist:
print i
Output:
11
12
13
14
15
A for loop over an empty list never executes the body and is shown in the following code:
numlist = []
for i in numlist:
print ‘never executes’

4.1.6 Mutability
The list is a mutable data structure. This means that its elements can be replaced, inserted
and removed. A slice operator on the left side of an assignment operation can update single or
multiple elements of a list. New elements can be added to the list using append() method.

The following code replaces ‘Ram’ which is at index 0 in the stulist by ‘Priya’. The values
are shown in the output for both instances.
stulist = [‘Ram’, ‘Chennai’, 2017]
Compound Data: Lists, Tuples, Dictionaries 4.9

print ‘Before mutation ‘, stulist


stulist[0] = ‘Priya’
print ‘After mutation ‘, stulist

Output:
Before mutation [‘Ram’, ‘Chennai’, 2017]
After mutation [‘Priya’, ‘Chennai’, 2017]

4.1.7 Aliasing
When we create two lists, we get two objects as shown in the following code and the
corresponding state diagram (Figure 4.1):

list1=[1,2]
list2=[1,2]
print list1 is list2 # prints False, as list1 and list2 are not the same object

List 1 [1,2]

List 2 [1,2]

Figure 4.1. State Diagram


Here, the two lists list1 and list2 are equivalent since they have the same elements. But
they are not identical since they are not the same object. If two objects are identical, then they are
equivalent. But if two objects are equivalent, then they are not necessarily identical.

In the following code, there are two references to the same object. An object with more than
one reference has more than one name, so we say that the object is aliased.
list1=[1,2]
list2=list1
print list1 is list2 # prints True, as list1 and list2 are the same object

The state diagram for the above code is as shown in Figure 4.2:

List 1
[1,2]
List 2

Figure 4.2. State Diagram


If the aliased object is mutable, modifications done in one object affect the other object
also. In the following code, list1 and list2 are aliased objects. Changes made in list1 affect list2 and
similarly, changes done in list2 affect list1.
4.10 Problem Solving and Python Programming

Sample Code
list1=[1,2]
list2=list1
print ‘List1 is :’, list1
print ‘List2 is :’, list2
list1[0]=10
print ‘List1 is :’, list1
print ‘List2 is :’, list2
list2[1]=20
print ‘List1 is :’, list1
print ‘List2 is :’, list2

Sample Output:
List1 is : [1, 2]
List2 is : [1, 2]
List1 is : [10, 2]
List2 is : [10, 2]
List1 is : [10, 20]
List2 is : [10, 20]

Though aliasing can be helpful, it may lead to errors. So, avoid aliasing in mutable objects.
To prevent aliasing in lists, a new empty list can be created and the contents of the existing list can
be copied to it, as given in the following code:

list1=[1,2] # Existing list


list2=[] # New and Empty list
for e in list1:
list2.append(e)
print ‘List1 is :’, list1
print ‘List2 is :’, list2
list1[0]=10
print ‘After modification’
print ‘List1 is :’, list1
print ‘List2 is :’, list2
Compound Data: Lists, Tuples, Dictionaries 4.11

Output:
List1 is : [1, 2]
List2 is : [1, 2]
After modification
List1 is : [10, 2]
List2 is : [1, 2]

4.1.8 Cloning Lists


Assignment statements in Python do not copy objects. They simply create bindings between
two objects. For mutable sequences (like lists), a copy of an existing object may be required so that
one object can be changed without affecting another.

In lists, cloning operation can be used to create a copy of an existing list so that changes
made in one copy of list will not affect another. The copy contains the same elements as the original.

Method 1:  list() function:
Built-in list() function can be used for cloning lists with the following syntax:
Newlistname = list(Oldlistname)

Sample Code:
oldlist = [10, 20, 30, 40, 50]
newlist = list(oldlist)
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
oldlist[0]=5
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist

Sample Output:
Old list is : [10, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]
Old list is : [5, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]

Method 2:  copy.copy() function:
Syntax:
Newlistname = copy.copy(Oldlistname)
copy.copy() is little slower than  list() since it has to determine data type of  old
list first.
4.12 Problem Solving and Python Programming

Sample Code:
import copy
oldlist = [10, 20, 30, 40, 50]
newlist = copy.copy(oldlist) # Returns a shallow copy of oldlist
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
oldlist[0]=5
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist

Sample Output:
Old list is : [10, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]
Old list is : [5, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]

Method 3:  copy.deepcopy() function:
Syntax
Newlistname = copy.deepcopy(Oldlistname)

copy.deepcopy() is the slowest and memory-consuming method.

Sample Code:
import copy
oldlist = [10, 20, 30, 40, 50]
newlist = copy.deepcopy(oldlist) # Returns a deep copy of oldlist
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
oldlist[0]=5
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist

Sample Output:
Old list is : [10, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]
Old list is : [5, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]
Compound Data: Lists, Tuples, Dictionaries 4.13

copy() (also known as shallow copy) and deepcopy() differs in the usage of compound objects
that are objects containing other objects, like lists). copy() creates a new compound object first and
then inserts references to the objects of the original. deepcopy() constructs a new compound object
and then, recursively, inserts copies to the objects of the original. The following code illustrates the
use of deepcopy() for a compound (nested) list.

Sample Code:
import copy
oldlist = [1, 2, [‘a’,’b’]]
newlist = copy.deepcopy(oldlist)
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
newlist[0] = ‘c’
newlist[2][1] = ‘d’
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist

Sample Output:
Old list is : [1, 2, [‘a’, ‘b’]]
New list is : [1, 2, [‘a’, ‘b’]]
Old list is : [1, 2, [‘a’, ‘b’]]
New list is : [‘c’, 2, [‘a’, ‘d’]]

4.1.9 List Parameters


When a list is passed as a parameter to a function, the function gets a reference to the list. In
the following code, numlist is a list and it is passed as a parameter to my_insert() function. Within
my_insert(), it is referenced as t.
def my_insert(t): # function definition
t.insert(1,15)
numlist = [10, 20, 30, 40, 50]
print ‘Before calling my_insert function : ‘, numlist
my_insert(numlist) # function call
print ‘After calling my_insert function : ‘, numlist
Here, the parameter t and the variable numlist are aliases for the same object. my_insert()
function inserts a new element 15 at index 1 in the list. This change is visible to the caller. The
elements of a list before and after calling my_insert() are given below as the output:
Before calling my_insert function : [10, 20, 30, 40, 50]
After calling my_insert function : [10, 15, 20, 30, 40, 50]
4.14 Problem Solving and Python Programming

The following program employs a function my_display() that creates and returns a new list.
Within my_display(), numlist is referenced as n.

Sample Code:
def my_display(n): # function definition
return n[:]
numlist = [10, 20, 30, 40, 50]
print ‘numlist is : ‘, numlist
newlist=my_display(numlist) # function call
print ‘newlist is : ‘, newlist

Sample Output:
numlist is : [10, 20, 30, 40, 50]
newlist is : [10, 20, 30, 40, 50]
The following program includes a function my_display() that creates and displays the
elements of a list.

Sample Code:
def my_display(n): # function definition
nlist= n[:]
print ‘Within a function : ‘, nlist
numlist = [10, 20, 30, 40, 50]
print ‘numlist is : ‘, numlist
my_display(numlist) # function call

Sample Output:
numlist is : [10, 20, 30, 40, 50]
Within a function : [10, 20, 30, 40, 50]

4.1.10 Deleting List Elements


To remove a list element, del operator can be used if an element to be deleted is known. In
the following code, the element ‘Chennai’ is deleted by mentioning its index in the del operator.

stulist = [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]


print ‘Initial list is : ‘, stulist
del stulist[1]
print ‘Now the list is : ‘, stulist
Compound Data: Lists, Tuples, Dictionaries 4.15

Output:
Initial list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
Now the list is : [‘Ram’, 2017, ‘CSE’, 92.7]
pop() and remove() methods can also be used to delete list elements.

4.1.11 Python Functions for List Operations


1. cmp
Compares two lists and returns 0, if they are equal. Else, returns a nonzero vale.

Syntax: cmp(list1, list2)

Code Output
list1 = [10, ‘xyz’]
list2 = [20, ‘abc’]
list3 = [10, ‘xyz’]
print ‘Comparing list1 and list2 ‘, cmp(list1, list2) Comparing list1 and list2 -1
print ‘Comparing list2 and list3 ‘, cmp(list2, list3) Comparing list2 and list3 1
print ‘Comparing list1 and list3 ‘,cmp(list1, list3) Comparing list1 and list3 0

1. len
Returns the total number of elements in a list.

Syntax: len(listname)
Code Output
stulist = [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
print ‘Length is : ‘, len(stulist) Length is : 5

2. max
Returns the largest item from the list.
Syntax: max(listname)

3. min
Returns the smallest item from the list.
Syntax: min(listname)
Code Output
numlist = [6, 28, 11, 4, 20, 26, 13, 12]
print ‘Maximum is : ‘, max(numlist) Maximum is : 28
print ‘Minimum is : ‘, min(numlist) Minimum is : 4
4.16 Problem Solving and Python Programming

stulist = [‘Anu’, ‘Chennai’, 2017, ‘CSE’, 92.7]


print ‘Maximum is : ‘, max(stulist) Maximum is : Chennai
print ‘Minimum is : ‘, min(stulist) Minimum is : 92.7

4. list
Converts a tuple into a list and returns a list.
Syntax: listname=list(tuplename)
Code Output
stu_tuple = (‘Anu’, ‘Chennai’, 2017, ‘CSE’, 92.7) Tuple elements : (‘Anu’, ‘Chennai’,
print ‘Tuple elements : ‘, stu_tuple 2017, ‘CSE’, 92.7)
stulist = list(stu_tuple) List elements : [‘Anu’, ‘Chennai’,
print ‘List elements : ‘, stulist 2017, ‘CSE’, 92.7]

4.1.12 List Comprehension


Comprehensions are constructs that allow sequences to be built from other sequences. It
provides a concise way to create lists. Python 2.0 introduced list comprehensions and Python 3.0
comes with dictionary and set comprehensions.

A list comprehension consists of the following parts:


•• An Input Sequence.
•• Variable representing members of the input sequence.
•• An Optional Predicate expression.
•• An Output Expression producing elements of the output list from members of the Input
Sequence that satisfy the predicate.

Syntax:
[expression for item in list if conditional]
This is equivalent to:
for item in list:
if conditional:
expression
new_list = [expression(i) for i in old_list if filter(i)]

new_list is the resultant list. expression(i) is based on the variable used for each element in
the old list. If needed filter can be applied using if statement.

Example:
from types import *
a_list = [1, ‘4’, 9, ‘a’, 0, 4]
Compound Data: Lists, Tuples, Dictionaries 4.17

squared_ints = [ e**2 for e in a_list if type(e) == IntType ]


print squared_ints

Sample output:
[ 1, 81, 0, 16 ]
Output Input
Expression Sequence

e**2 for e in a _list if type (e) == types.IntType

variable Optional Predicate

•• The iterator part iterates through each member e of the input sequence a_list.
•• The predicate checks if the member is an integer.
•• If the member is an integer then it is passed to the output expression, squared, to become
a member of the output list.

Example:
x=[I for I in range(10)]
print x
Sample Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
squares=[x**2 for x in range(10)]
print squares

Sample Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

str=[“this”, “is”, “an”, “example”]


items=[word[0] for word in str]
print items

Sample Output:
[‘t’, ‘i’, ‘a’, ‘e’]

value=[x+y for x in [10,20,30] for y in [1,2,3]]


print value
4.18 Problem Solving and Python Programming

Sample Output:
[11, 12, 13, 21, 22, 23, 31, 32, 33]
This example, adds the values in list x to each value in list y.

4.2 TUPLES
A tuple is a collection of values of different types. Unlike lists, tuple values are indexed by
integers. The important difference is that tuples are immutable.

4.2.1 Advantages of Tuple over List


Tuples are like lists, so both of them are used in similar situations as well. However, there
are specific advantages of implementing a tuple over a list. The advantages of tuples over list are
listed below.

•• Tuples generally used for heterogeneous (different) datatypes and list for homogeneous
(similar) datatypes.
•• Tuples are immutable, so iterating through tuple is faster than the list. There is a slight
performance enhancement through list.
•• Tuple elements can be used as key for a dictionary. With list, this is not possible.
•• If you have data that doesn’t change, implementing it as tuple will guarantee that it
remains write-protected.
As we have seen before, a tuple is a comma-separated values.
Syntactically, a tuple can be represented like this:
>>> t = ‘a’, ‘b’, ‘c’, ‘d’, ‘e’
Even if it is not necessary to parentheses to enclose tuples, it is so.
t1 = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
t2=(1,2,3,4,5)
The empty tuple can be created by simply using the parentheses.
t3=()
The tuple with one element can be created as follows. It takes one comma after the element.
t4=(‘s’,)
print type(t4)

Output:
<type ‘tuple’>
t5 = ‘a’,
print type(t5)
Compound Data: Lists, Tuples, Dictionaries 4.19

Output:
<type ‘tuple’>
A value of tuple in parentheses is not a tuple. The following program code explain this.
t2 = (‘a’)
print type(t2[1])

Output:
<type ‘str’>

The built –in function tuple can be used to create tuple. To create an empty tuple no arguments
is passed in the built-in function.
t = tuple() #tuple is the built-in function
print t

Output:
()

If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of
the sequence:

t = tuple(‘hello’)

print t

Output:
(‘h’, ‘e’, ‘l’, ‘l’, ‘o’)

t = tuple(’12345’)

print t

Output:
(‘1’, ‘2’, ‘3’, ‘4’, ‘5’)

Program to illustrate the tuple creation for single element


# only parentheses is not enough
tup1 = (“hai”)
print type(tup1)
# need a comma at the end
tup2 = (“hai”,)
print type(tup2)
4.20 Problem Solving and Python Programming

# parentheses is optional
tup3 = “hai”,
print type(tup3)

Output:
<class ‘str’>
<class ‘tuple’>
<class ‘tuple’>

4.2.2 Accessing Values


To access the tuple elements slicing (bracket operator [ ] ) operator along with index or
indices is used.

t1 = (‘C’, ‘C++’, ‘python’, 1997, 2000);


t2 = (1, 2, 3, 4, 5, 6, 7 );
t3= (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
print “tup1[0]: “, tup1[0]
print “tup1[1]: “, tup1[1]

print “tup2[1:5]: “, tup2[1:5]


print “tup2[1:]: “, tup2[1:]
print t[0]

Output:
tup1[0]: C
tup1[1]: C++
tup2[1:5]: [2, 3, 4, 5, 6, 7]
a

Program to illustrate the accessing the tuple elements


t1 = [‘p’,’y’,’t’,’h’,’o’,’n’]
print t1[0]
print t1[5]
print t1[2]
print t1[-1]
print t1[-6]
# TypeError: list indices must be integers, not float
Compound Data: Lists, Tuples, Dictionaries 4.21

#t1[2.0]
# nested tuple
nest_tup = (“hello”, [8, 4, 6], (1, 2, 3))
# nested index
print nest_tup[0][4]
# nested index
# Output: 4
print nest_tup[1][2]
print nest_tup[2][0]

Output:
p
n
t
n
p
o
6
1

4.2.3 Updating Tuples


Tuples are immutable means that the tuple values cannot be updated or changed. However,
the portions of existing tuples are added with a new tuple to create another tuple as the following
example demonstrates −
Consider the following tuple,
t3= (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
No elements can be modified. If you try to modify, you will get an error.
t3[1]= ‘B’
TypeError: ‘tuple’ object does not support item assignment
Instead of modifying an element in the tuple sequence, it is obvious to simply replace one
tuple with another:
t3 = (‘A’,) + t3 [1:]
print t

Output:
(‘A’, ‘b’, ‘c’, ‘d’, ‘e’)
4.22 Problem Solving and Python Programming

Here, the first element ‘a’ is replaced with ‘A’. A new tuple is created with the value ‘A’ is
combined with tuple t3 having index from 1 to the last element. The tuple value t3[0]=’a’ is replaced
by ‘A’.

4.2.4 Delete Tuple Elements


It is impossible to delete a single element in the tuple. There is, of course, nothing wrong
with putting together another tuple with the undesired elements discarded. To delete an entire tuple,
the keyword del is used. For example:
t1 = (‘C’, ‘C++’, ‘python’, 1997, 2000);
print t1
del t1
print “After deleting : “
print t1

Output:
(‘C’, ‘C++’, ‘python’, 1997, 2000)

After deleting :

Traceback (most recent call last):

File “main.py”, line 5, in

print t1

NameError: name ‘t1’ is not defined

Program for updating and deleting tuples


t1 = (2, 3, 4, [5, 6])
print t1
# we cannot change an element
# TypeError: ‘tuple’ object does not support item assignment
#my_tuple[1] = 6; creates error
# but item of mutable element can be changed
t1[3][0] = 7
print t1
# tuples can be reassigned
t1 = (‘h’,’e’,’l’,’l’,’o’)
print t1
# Concatenation
Compound Data: Lists, Tuples, Dictionaries 4.23

print (1, 2, 3) + (4, 5, 6)


# Repetition operator
Print (“Repeat”,) * 3
#delete tuple
del t1
print t1
Output:
(2, 3, 4, [5, 6])
(2, 3, 4, [7, 6])
(‘h’, ‘e’, ‘l’, ‘l’, ‘o’)
(1, 2, 3, 4, 5, 6)
(‘Repeat’, ‘Repeat’, ‘Repeat’)
Traceback (most recent call last):
File “<stdin>”, line 25, in <module>
print(t1)
NameError: name ‘t1’ is not defined

4.2.5 Tuple Assignment


Tuple assignment makes it possible to create and assign values for more than one tuple in a
single statement itself. For example,
x, y = 1, 2
print x
print y

Output:
1
2
In general to swap the values of two variables, a temporary variable is used. For example
to swap x and y:
temp = x
x=y
y = temp
This solution is clumsy; the tuple assignment is more elegant.
a, b = b, a
In the expression, the left side is a tuple of variables; the right side is a tuple of expressions.
4.24 Problem Solving and Python Programming

Each value is assigned to its respective variable. All the expressions on the right side are evaluated
before any of the assignments.
The number of variables on the left side and the number of values on the right must be the
same:
a, b = 1, 2
In this a is assigned with 1 and b is assigned with 2.
For the assignment,
a, b= 1,2,3
This statement creates error, as
ValueError: too many values to unpack
The right side of the assignment statement can be any kind of sequence (string, list or tuple).
For example, to split an email address into a user name and a domain, the split function can be used
as follows.

mail_id = ‘students@python.org’
uname, domain = mail_id.split(‘@’)
print uname
print domain

Output:
students
python.org
In this, the split function is used to separate the value into two parts. The return value from
the split function is a list with two elements; the first element is assigned to uname, the second is
assigned to domain.

Program to illustrate tuple creation and assignment


# empty tuple
t1 = ()
print t1
# tuple having integers
t2 = (1, 2, 3)
print t2
# tuple with mixed datatypes
t3 = (1, “Hello”, 2.4)
print t3
# nested tuple
Compound Data: Lists, Tuples, Dictionaries 4.25

t4 = (“World”, [8, 4, 6], (1, 2, 3))


print t4
# tuple can be created without parentheses (called tuple packing)
t5 = 3, 4.6, “ABC”
print t5
# tuple unpacking is also possible
#tuple assignment
x, y, z = t5
print x
print y
print z

Output:
()
(1, 2, 3)
(1, ‘Hello’, 2.4)
(‘World’, [8, 4, 6], (1, 2, 3))
(3, 4.6, ‘ABC’)
3
4.6
ABC

4.2.6 Tuple Methods


In python methods for adding items and deleting items are not available. The methods
available are count and index.
•• count(x) method returns the number of occurrences of x
•• index(x) method returns index of the first occurrence of the item x.

Program for count and index methods


t1 = (‘p’,’y’,’t’,’h’,’o’,’n’,’p’,’r’,’o’,’g’,’r’,’a’,’m’)
# Count
print(t1.count(‘p’))
# Index
print t1.index(‘y’)
print t1.index(‘h’)
4.26 Problem Solving and Python Programming

Output:
2
1
3

4.2.7 Other Tuple Operations


There are some other tuple operations such as tuple membership test and iterating through a
tuple. Tuple Membership Test operation can test if an item exists in a tuple or not, using the keyword
in and not in. Iterating through a Tuple operation is performed using a for loop in which we can
iterate through each item in a tuple.

Simple program to illustrate tuple operations


t1 = (‘p’,’y’,’t’,’h’,’o’,’n’)
# In operation
print(‘y’ in t1)
# Output: False
print(‘m’ in t1)
# Not in operation
print(‘h’ not in t1)
print(‘a’ not in t1)
for lang in (‘C’,’C++’):
print(“Progrmming-languages”,lang)

Output:
True
False
False
True
Progrmming-languages C
Progrmming-languages C++

4.2.8 Tuples as Return Values


In general a function can return only one value, but if the return value is a tuple, then it
is returning multiple values. For example, to divide two integers and compute the quotient and
remainder, normally it is used to compute x/y and then x%y. But using python, it is better to compute
them both at the same time. The following code explains this
t = divmod (7, 3)
print t
Compound Data: Lists, Tuples, Dictionaries 4.27

Output:
(2, 1)

Here, the built-in function divmod is used which takes two arguments and returns a tuple of
two values, the quotient and remainder. The result can be stored as a tuple as in previous program
code. Or tuple assignment can be used to store the elements separately as in the following code.

quot, rem = divmod(7, 3)


print quot
print rem

Output:
2
1
One more example to explain tuples as return values. The built-in functions min and max
are used to find the smallest and largest elements of a sequence. The function min_max computes
both and returns a tuple of two values.

Here is an example of a function that returns a tuple:


def min_max(t):
return min(t), max(t)

4.2.9 Built-in Functions with Tuple


Function Description
all() Return True if all elements of the tuple are true (or if the tuple is empty).
any() Return True if any element of the tuple is true. If the tuple is empty, return False.
Return an enumerate object. It contains the index and value of all the items of
enumerate()
tuple as pairs.
len() Return the length (the number of items) in the tuple.
max() Return the largest item in the tuple.
min() Return the smallest item in the tuple
Take elements in the tuple and return a new sorted list (does not sort the tuple
sorted()
itself).
sum() Return the sum of all elements in the tuple.
tuple() Convert an iterable (list, string, set, dictionary) to a tuple.

4.2.10 Variable-length Argument Tuples


The functions can take a variable number of arguments for implementation. A argument
name that starts with (*) gathers the several arguments into a tuple. For example, printall
function takes any number of arguments and prints them:
4.28 Problem Solving and Python Programming

Example:
def printall (*args): # the function takes several args
print args

The argument name may be anything, but args is conventional. Here is the example to show
how the function printall works:
printall(1, 2.0, ‘3’)
(1, 2.0, ‘3’)
The complement of gather is scatter. To pass a sequence of values to a function as multiple
arguments, the * operator can be used. For example, consider the divmod function which takes
exactly two arguments; doesn’t work with a tuple of variable length arguments:
t = (7, 3)
divmod(t)

Output:
TypeError: divmod expected 2 arguments, got 1
But if you scatter the tuple, it works:
Instead of the above code, the code given below can be used for variable length arguments.
divmod(*t)
(2, 1)
There are some other built-in functions which use variable-length argument tuples.
The max and min functions take any number of arguments:
max(1,2,3)

Output:
3
The sum function does not take variable length arguments. It gives error.
sum(1,2,3)

Output:
TypeError: sum expected at most 2 arguments, got 3

4.2.11 Comparing Tuples


With relational operators it is possible to work with tuples and other sequences. To compare
two elements, Python starts by comparing the first element from each sequence. If the elements
are equal, it goes on to the next elements, and so on, until it finds an element that is different.
Subsequent elements are not considered (even if they are really big).
Compound Data: Lists, Tuples, Dictionaries 4.29

>>> (0, 1, 2) < (0, 3, 4)

True
The sort function also works in the same way. It sorts primarily by first element. But if there
is a tie, it sorts by second element, and so on. This feature lends itself to a pattern called DSU. DSU
stands for Decorate, Sort, Undecorate.

DSU:
Decorate a sequence by building a list of tuples with one or more sort keys preceding the
elements from the sequence,

Sort the list of tuples, and Undecorate by extracting the sorted elements of the sequence.

For example, to sort a list of words from longest to shortest:

def sort_by_length (words):


t = []
for word in words:
t.append((len(word), word))
t.sort(reverse=True)
res = []
for length, word in t:
res.append(word)
return res
The first loop builds a list of tuples, where each tuple is a word preceded by its length.
The sort function compares the first element, and its length first, and only considers the second
element to break ties. The keyword argument reverse=True tells sort to go in decreasing order. The
second loop traverses the list of tuples and builds a list of words in descending order of length. The
following program explains the comparison function.

t1, t2 = (123, ‘xyz’), (456, ‘abc’)


print cmp (t1, t2)
print cmp (t2, t1)
t3 = t2 + (786, )
print cmp (t2, t3)
print cmp (t3, t2)
t3, t4= (‘hello’, 3) , (‘hello’, 3)
print cmp (t3, t4)
print cmp (t4,t3)
4.30 Problem Solving and Python Programming

t5,t6 = (3, ‘hai’), (‘hai’,3)


print cmp (t5, t6)
print (t6, t5)

Output:
-1
1
-1
1
0
0
-1
1

4.3 DICTIONARIES
Dictionary is an unordered collection of items. It is similar to a list, but in list elements can
be accessed using index which must be an integer. In Dictionary we access values by looking up a
key instead of an index. A key can be any string or number. For example, dictionaries can be used
for things like phone books (pairing a name with a phone number), login pages (pairing an e-mail
address with a username).

Each item in dictionary has a key: value pair and the list of items are enclosed inside curly
braces {} separated by comma. The values can be of any data type and can repeat; keys must be of
immutable types (string, number or tuple with immutable elements) and must be unique.

Dictionaries in Python are implemented using hash table. It is an array whose indexes are
obtained using a hash function on the keys. A hash function takes a key value and returns hash
value, an integer. This hash value is used in the dictionary to store and lookup key-value pairs. So
keys in dictionary must be hashable.

The following code is a simple example which creates an empty dictionary.

# empty dictionary
my_dict = {}
print my_dict

Sample Output:
{}
The following dictionary uses integer as keys and string as values.
# dictionary with integer keys
Compound Data: Lists, Tuples, Dictionaries 4.31

my_dict = {1: ‘apple’, 2: ‘ball’}


print my_dict
print my_dict[2]

Sample Output:
{1: ‘apple’, 2: ‘ball’}   
ball 

The following dictionary uses mixed keys. For item 1, both key and its corresponding value
are string. In item 2, the key is an integer and the value is a list.

# dictionary with mixed keys


my_dict = {‘name’: ‘John’, 1: [2, 4, 3]}
print my_dict
print my_dict[‘name’]
print my_dict[1]

Sample Output:
{1: [2, 4, 3], ‘name’: ‘John’}  
John  
[2, 4, 3]
In the output, the order of the key-value pairs is not the same. In general, the order of items
in dictionary is unpredictable. In the following example, using list, a mutable data type as key
results in error message.

dic = { [1,2,3]:”abc”}
Traceback (most recent call last):   
File “main.py”, line 1, in <module> 
dic = { [1,2,3]:”abc”}  
TypeError: unhashable type: ‘list’
Tuple, an immutable data type can be used as key, which is shown in following example.
my_dic = { (1,2,3):”abc”, 3.14:”abc”}
print my_dic

Sample Output:
{3.14: ‘abc’, (1, 2, 3): ‘abc’}  
An exception will be raised when we try to access a key that does not exist in dictionary. In
the following example, accessing my_dict[2] results in an error, as the key 2 not exist in dictionary.
4.32 Problem Solving and Python Programming

my_dict = {‘name’: ‘John’, 1: [2, 4, 3]}


print my_dict[2]

Sample Output:
Traceback (most recent call last):  
File “main.py”, line 2, in <module>
 print my_dict[2] 
KeyError: 2 

Dictionaries can also be created using the dict() function.


# using dict()
my_dict = dict({1:’apple’, 2:’ball’})
print my_dict

Sample Output:
{1: ‘apple’, 2: ‘ball’}

4.3.1 Built-in Dictionary Functions & Methods


Built-in methods or functions that are available with dictionary are tabulated below.

Function/Method Description
len(dict) Returns the length of dictionary which is equal to
number of pairs in the dictionary.
cmp(dict1,dict2) Compare items of two dictionaries
sorted(dict) Returns sorted list of keys in dictionary
dict.clear() Remove all items from dictionary
dict.copy() Returns a shallow copy of dictionary
dict.fromkeys(seq[, v]) Return a new dictionary with keys from seq and value
equal to v
dict.get(key) Returns the value of key. If key does not exists, it returns
None
dict.pop(key) Remove the item with key and returns its value.
KeyError occurs when key is not found
dict.popitem() Remove and return an arbitary item (key, value). Raises
KeyError if the dictionary is empty.
dict.items() Returns a list of dict’s (key, value) tuple pairs
dict.keys() Returns list of dictionary dict’s keys
dict1.update(dict2) Update the dictionary dict1 with the key/value pairs
from dict2, overwriting existing keys.
Compound Data: Lists, Tuples, Dictionaries 4.33

4.3.2 Access, Update, and Add Elements in Dictionary


Key can be used either inside square brackets or with the get() method. The difference while
using get() is that it returns None instead of KeyError, if the key is not found. Dictionary is mutable.
So we can add new items or change the value of existing items. If the key is present, its value gets
updated. Else a new key:value pair is added to dictionary.
my_dict={‘name’:’Ram’,’age’:21}
print my_dict # display all items
print my_dict.get(‘name’) # Retrieves the value of name key
my_dict[‘age’]=23 # update value
print my_dict
my_dict[‘dept’]=’CSE’ # add item
print my_dict
Sample Output:
{‘age’: 21, ‘name’: ‘Ram’}
{‘age’: 23, ‘name’: ‘Ram’}
{‘dept’: ‘CSE’, ‘age’: 23, ‘name’: ‘Ram’}

4.3.3 Delete or Remove Elements from a Dictionary


A particular item in a dictionary can be removed by using the method pop(). This method
removes an item with the provided key and returns the value. The method, popitem() can be used to
remove and return an arbitrary item (key, value) from the dictionary. All the items can be removed
at once using the clear() method.
squares={1:1,2:4,3:9,4:16,5:25}
print(squares.pop(3)) # remove a particular item
print squares
print (squares.popitem()) # remove an arbitrary item
print squares
del squares[5] # delete a particular item
squares.clear() # remove all items
print squares

Sample Output:
9
{1: 1, 2: 4, 4: 16, 5: 25}
(1, 1) 
{2: 4, 4: 16, 5: 25} 
{2: 4, 4: 16} 
{}
4.34 Problem Solving and Python Programming

We can also use the del keyword to remove individual items or the entire dictionary itself.
If we try to access the deleted dictionary, it will raise an Error.
del squares # delete the dictionary itself
print squares #throws error
Traceback (most recent call last): 
File “main.
py”, line 11, in <module> 
print squares NameError: name ‘squares’ is not defined 

4.3.4 Sorting a Dictionary


The items in dictionary can be sorted using sorted() function. In the following example,
fromkeys() function is used to create a dictionary from sequence of values. The value 0 is assigned for
all keys. Each item is accessed iteratively using for loop that iterate though each key in a dictionary.
marks={}.fromkeys([‘Math’,’English’,’Science’],0)
print marks
for item in marks.items():
print item
print list(sorted(marks.keys()))

Sample Output:
{‘Maths’: 0, ‘Science’: 0, ‘English’: 0}
(‘Maths’, 0)
(‘Science’, 0)
(‘English’, 0)
[‘English’, ‘Maths’, ‘Science’] 

4.3.5 Iterating Through a Dictionary


Using a for loop we can iterate though each key in a dictionary.
squares={1:1,2:4,3:9,4:16,5:25}
for i in squares:
print(squares[i])
Sample Output:



16
25 
Compound Data: Lists, Tuples, Dictionaries 4.35

4.3.6 Reverse Lookup


Lookup is the process of finding the corresponding value for the given key from dictionary.
It’s easy to find the value of a given key in a python dictionary.

value=dict[key]

Whereas, reverse lookup is the process of finding the key for a given value. There is no
direct method to handle reverse lookup. The following function takes a value and returns the first
key that map to that value.

def get_Value(dic,value):
for name in dic:
if dic[name] == value:
return name
raise ValueError
squares={1:1,2:4,3:9,4:16,5:25}
print get_Value(squares,4) # successful reverse lookup

Sample Output:
2
In this example, raise keyword is used to raise/activate an exception. ValueError indicates
that there is something wrong with value of parameter. On unsuccessful reverse lookup, when the
value is not in the dictionary, the exception ValueError is raised. Unsuccessful reverse lookup result
in following error.
print get_Value(squares,6) # unsuccessful reverse lookup
Traceback (most recent call last):  
File “main.py”, line 7, in <module>
print get_Value(squares,6)
File “main.py”, line 5, in get_Value 
raise ValueError
ValueError

4.3.7 Inverting a Dictionary


A dictionary can be inverted with list values. For example, if you were given a dictionary
that maps from child to parent, you might want to invert it; that is, create a dictionary that maps
from parent to children. Since there might be several children with the same parent each value in the
inverted dictionary should be a list of children.
4.36 Problem Solving and Python Programming

def invert_dict_nonunique(d):
newdict = {}
for k, v in d.iteritems():
newdict.setdefault(v, []).append(k)
return newdict
d = {‘child1’: ‘parent1’,
‘child2’: ‘parent1’,
‘child3’: ‘parent2’,
‘child4’: ‘parent2’,
}
print invert_dict_nonunique(d)

Sample Output:
{‘parent2’: [‘child3’, ‘child4’], ‘parent1’: [‘child1’, ‘child2’]} 

In this example the loop iterates through dictionary items where k represents key and v
represents value. The setdefault() method will set newdict[v]=[] and append the key value to list..

As we mentioned earlier, the keys in dictionaries have to be hashable. It works correctly


only when keys are immutable. For example, if key is a list and to store a key-value pair Python will
hash the key and store it in corresponding location. If that key is modified, it would be hashed to
different location. In this case, we will have two entries for the same key or might be failed to locate
a key. Either way, the dictionary wouldn’t work correctly. Since lists and dictionaries are mutable,
they can’t be used as keys, but they can be used as values.

4.3.8 Memoization (Memos)


Memoization effectively refers to remembering results of method calls based on the method
inputs and then returning the remembered result rather than computing the result again.

For example, consider the recursive version to calculate the Fibonacci numbers. The
following code to compute Fibonacci series has an exponential runtime behavior.

def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
Compound Data: Lists, Tuples, Dictionaries 4.37

The runtime behavior of this recursive version can be improved by adding a dictionary to
memorize previously calculated values of the function.

def memoize(f):
memo = {}
def helper(x):
if x not in memo:
memo[x] = f(x)
return memo[x]
return helper
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
fib = memoize(fib)
print(fib(6)) # output the 6th number in Fibonacci series (series starts from 0th
position)

Sample Output:
8
memoize() takes a function as an argument. The function memorize() uses a dictionary
“memo” to store the function results. Though the variable “memo” as well as the function “f” are
local to memoize, they are captured by a closure through the helper function which is returned as a
reference by memoize(). So, the call memoize(fib) returns a reference to the helper() which is doing
what fib() would do on its own plus a wrapper which saves the calculated results. For an integer ‘n’
fib(n) will only be called, if n is not in the memo dictionary. If it is in it, we can output memo[n] as
the result of fib(n).
4.38 Problem Solving and Python Programming

memoize

Memo = {}
def helper (x):
if x not in memo:
memo[x]=f(x) Executing;
return memo[x] fib = memoize(fib)
return helper helper is returned

fib

if x not in memo:
if n==0: memo [x]= f(x)
return 0 return memo [x]
elseif n==1:
return 1
else:
return fib(n-1) + fib(n-2)

After having executed fib = memoize(fib) fib points to the body of the helper function,
which had been returned by memoize. The decorated Fibonacci function is called in the return
statement return fib(n-1) + fib(n-2), this means the code of the helper function which had been
returned by memorize.

4.4 ILLUSTRATIVE PROGRAMS


4.4.1 Python program to sort a list of elements using the selection sort algorithm
Selection sort is a simple sorting algorithm. It is an in-place comparison-based algorithm
in which the list is divided into two parts: the sorted part at the left end and the unsorted part at the
right end. Initially, the sorted part is empty and the unsorted part is the entire list.

Selection sort algorithm starts by comparing first two elements of an array and swapping if
necessary, i.e., if you want to sort the elements of array in ascending order and if the first element
is greater than second then, you need to swap the elements but, if the first element is smaller than
second, leave the elements as it is. Then, again first element and third element are compared and
swapped if necessary. This process goes on until first and last element of an array is compared.
This completes the first step of selection sort. The working of selection sort algorithm is shown in
Figure.4.3.
Compound Data: Lists, Tuples, Dictionaries 4.39

20 12 10 15 2 2 20 12 15 10 2 10 20 15 12 2 10 12 20 15

12 20 10 15 2 2 12 20 15 10 2 10 15 20 12 2 10 12 15 20

10 20 12 15 2 2 12 20 15 10 2 10 12 20 15

10 20 12 15 2 2 10 20 15 12

2 20 12 15 10

Step 1 Step 2 Step 3 Step 4

Figure 4.3. Selection Sort

This algorithm is not suitable for large data sets as its average and worst case complexities
are of Ο(n2), where n is the number of items.

arr=[]
n=input(‘Enter number of elements’)
for i in range(0,n):
x=int(input(‘Enter number’))
arr.insert(i,x)
i+=1
for i in range(len(arr)):
for j in range(i, len(arr)):
if(arr[i] > arr[j]):
arr[i], arr[j] = arr[j], arr[i]
print ‘Sorted List:’, arr

Sample input/output:
Enter no5
enter no.12
 enter no. 2
enter no.23
enter no. 4 
enter no.5
Sorted List:
[2, 4, 5, 12, 23]   
4.40 Problem Solving and Python Programming

4.4.2 Python program to sort a list of elements using the insertion sort algorithm
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item
at a time. Here, a sub-list is maintained which is always sorted. The array is searched sequentially and
unsorted items are moved and inserted into the sorted sub-list (in the same array). This algorithm is
suitable for small data sets. But it is much less efficient on large lists than more advanced algorithms
such as quicksort, heapsort, or merge sort. The worst case complexity of the algorithm is of Ο(n2),
where n is the number of items. Insertion sort is explained in figure 4.4.

Checking second element of array with element


Step 1 12 3 1 5 8 before it and inserting it in proper position. In
this case, 3 is inserted in position of 12.

Checking third element of array with element


Step 2 3 12 1 5 8 before it and inserting it in proper position. In
this case, 1 is inserted in position of 3.

Checking fourth element of array with element


Step 3 11 3 12 5 8 before it and inserting it in proper position. In
this case, 5 is inserted in position of 12.

Checking fifth element of array with element


Step 4 12 3 5 12 8 before it and inserting it in proper position. In
this case, 8 is inserted in position of 12.

12 3 5 8 12 Sorted Array in Ascending Order

Figure 4.4. Insertion Sort

def insertionsort(list):
for i in range(1,len(list)):
temp=list[i]
j=i-1
while temp<+list[j] and j>=0:
list[j+1]=list[j]
j=j-1
list[j+1]=temp
return list
arr=[]
n=input(‘Enter number of elements’)
for i in range(0,n):
x=int(input(‘Enter number’))
arr.insert(i,x)
i+=1
print insertionsort(arr)
Compound Data: Lists, Tuples, Dictionaries 4.41

Sample input/output:
Enter number of elements5
Enter number12
Enter number23
Enter number4 
Enter number16
Enter number34
[4, 12, 16, 23, 34] 

4.4.3 Python program to sort a list of elements using the merge sort algorithm
Merge sort is a sorting technique based on divide and conquer technique. It first divides the
array into equal halves and then combines them in a sorted manner. The basic steps involved in
merge sort algorithm are as follows: Given an array A.

1. Divide
If q is the half-way point between p and r, then we can split the subarray A[p..r] into two
arrays A[p..q] and A[q+1, r].

2. Conquer
In the conquer step, we try to sort both the subarrays A[p..q] and A[q+1, r]. If we haven’t yet
reached the base case, we again divide both these subarrays and try to sort them.

3. Combine
When the conquer step reaches the base step and we get two sorted subarrays A[p..q] and
A[q+1, r] for array A[p..r], we combine the results by creating a sorted array A[p..r] from
two sorted subarrays A[p..q] and A[q+1, r].
38 27 43 3 9 82 10

38 27 43 3 9 82 10

38 27 43 3 9 82 10

38 27 43 3 9 82 10

27 38 3 43 9 82 10

3 27 38 43 9 10 82

3 9 10 27 38 43 82

Figure 4.5. Merge Sort


4.42 Problem Solving and Python Programming

As shown in Figure. 4.5, the merge sort algorithm recursively divides the array into halves
until we reach the base case of array with 1 element. After that, the merge function picks up the
sorted sub-arrays and merges them to gradually sort the entire array. The worst case complexity of
the algorithm is O(n log n), where n is the number of items.
def merge_sort(sequence):
if len(sequence) < 2:
return sequence
m = len(sequence) / 2
return merge(merge_sort(sequence[:m]), merge_sort(sequence[m:]))
def merge(left, right):
result = []
i=j=0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
print merge_sort([5, 2, 6, 8, 5, 8, 1])

Sample output:
[1, 2, 5, 5, 6, 8, 8]

4.4.4 Python program to sort a list of elements using the Quick sort algorithm
Like Merge Sort, Quick Sort is a Divide and Conquer algorithm. It picks an element as
pivot and partitions the given array around the picked pivot. The pivot element can be selected using
following different ways.
(1) Always pick first element as pivot.
(2) Always pick last element as pivot.
(3) Pick a random element as pivot.
(4) Pick median as pivot.

The runtime of the algorithm varies based on the pivot selected. The basic idea behind this
algorithm is as follows.
1. Pick one element in the array, which will be the pivot.
2. Make one pass through the array, called a partition step, re-arranging the entries so that:
Compound Data: Lists, Tuples, Dictionaries 4.43

i) The pivot is in its proper place.


ii) Entries smaller than the pivot are to the left of the pivot.
iii) Entries larger than the pivot are to its right.
3. Recursively apply quick sort to the part of the array that is to the left of the pivot,
and to the right part of the array.
The steps involved in quick sort algorithm are listed below and can be understood easily
using the example shown in Figure.4.6.
Step 1 − Choose the highest index value has pivot
Step 2 − Take two variables to point left and right of the list excluding pivot
Step 3 − left points to the low index
Step 4 − right points to the high
Step 5 − while value at left is less than pivot move right
Step 6 − while value at right is greater than pivot move left
Step 7 − if both step 5 and step 6 does not match swap left and right
Step 8 − if left ≥ right, the point where they met is new pivot
54 26 93 17 77 31 44 55 20 54 will be the first pivot value

54 53 93 17 77 31 44 55 20 Leftmark and rightmark will


converge on split point

leftmark rightmark

54 26 93 17 77 31 44 55 20 26<54 move to right 93>54


stop
leftmark rightmark

54 26 93 17 77 31 44 55 20 now rightmark 20<54 stop

leftmark rightmark

54 26 20 17 77 31 44 55 93 exchange 20 and 93

leftmark rightmark

Now continue moving leftmark and rightmark


77 > 54 stop
54 26 20 17 77 31 44 55 93 44 < 54 stop
exchange 77 and 44

leftmark rightmark
77 > 54 stop
54 26 20 17 44 31 77 55 93 31 < 54 stop
rightmark < leftmark
split point found
rightmark leftmark exchange 54 and 31

until they cross

Figure 4.6. Quick Sort


4.44 Problem Solving and Python Programming

# divide part of the algorithm


def partition(myList, start, end):
pivot = myList[start]
left = start+1
right = end
done = False
while not done:
while left <= right and myList[left] <= pivot:
left = left + 1
while myList[right] >= pivot and right >=left:
right = right -1
if right < left:
done= True
else:
# swap places
temp=myList[left]
myList[left]=myList[right]
myList[right]=temp
# swap start with myList[right]
temp=myList[start]
myList[start]=myList[right]
myList[right]=temp
return right
# conquer part of the quicksort routine
def quicksort(myList, start, end):
if start < end:
# partition the list
pivot = partition(myList, start, end)
# sort both halves
quicksort(myList, start, pivot-1)
quicksort(myList, pivot+1, end)
return myList
List = [54,26,93,17,77,31,44,55,20]
print quicksort(List)

Sample Output:
[17, 20, 26, 31, 44, 54, 55, 77, 93]
Compound Data: Lists, Tuples, Dictionaries 4.45

4.4.5 Write a Python program to create a histogram from a given list of integers.
def histogram( items ):
for n in items:
output = ''
times = n
while( times > 0 ):
output += '*'
times = times - 1
print(output)
histogram([2, 3, 6, 5])

Sample Output:
**
***
******
*****
UNIT - 5

FILES, MODULES, PACKAGES

5.1 FILES
5.1.1 Reading and Writing
So far in the previous chapters, we have seen to work standard input and output through
input functions such as input () and raw_input() and output function print statement.

The raw_input Function:
The  raw_input([prompt]) function reads one line from standard input and returns it as a
string (leaving the trailing newline).

s = raw_input(“Enter your input: “);


print “ Entered input is : “, s

Output:
Enter your input: Hello Python
Received input is : Hello Python

The input Function
The input([prompt]) function is similar to raw_input, except that it assumes the input as a
valid Python expression and returns the evaluated result.

s = input(“Enter your input: “);


print “ The output is : “, str

Output:
Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40]

Now, we will see how to use actual data files. A text file is a sequence of characters stored on
a permanent storage medium such as hard drive, flash memory, or CD-ROM. Python offers some
basic functions and methods necessary to manipulate files by default. The file manipulation can be
done using a file object. The basic file operations are open, close, read and write files.
5.2 Problem Solving and Python Programming

The open Function
To read or write a file, it is necessary to open it using Python’s built-in  function named
open() function. The open() function creates a file object that could be used to call other methods
associated with it. The syntax for open() function is shown below.

Syntax
fileobject = open(file_name [, access_mode][, buffering])

The parameters are explained below:


•• file_name: The file_name argument is a string value that contains the name of the file
to access.
•• access_mode: The access_mode denotes the mode in which the file has to be opened
(read, write, append, etc). A complete list of possible values is mentioned below in the
table. This parameter is optional and the default file access mode is read (r).
•• buffering: If the buffering value is set to 0, then there is no buffering takes place. If
the buffering value is 1, then line buffering is performed while accessing a file. If the
buffering value is set to an integer greater than 1, then buffering action is performed
with the indicated buffer size. If the buffering value is negative, then the buffer size is
the system default (default behavior).

The list of different file opening modes –


Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed at the beginning
of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer placed at the beginning of
the file.
rb+ Opens a file for both reading and writing in binary format. The file pointer placed at
the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If
the file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists.
If the file does not exist, creates a new file for reading and writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file
if the file exists. If the file does not exist, creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file
for writing.
Files, Modules, Packages 5.3

ab Opens a file for appending in binary format. The file pointer is at the end of the file if
the file exists. That is, the file is in the append mode. If the file does not exist, it creates
a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file if
the file exists. The file opens in the append mode. If the file does not exist, it creates a
new file for reading and writing.
ab+ Opens a file for both appending and reading in binary format. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If the file does not
exist, it creates a new file for reading and writing.

The file Object Attributes
Once a file is opened, there would be one file object, to get various information related to
that file.
Here is a list of all attributes related to file object:

Attribute Description
file.closed Returns true if the file is closed, otherwise false.
file.mode Returns the file access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with print, otherwise true.

The following illustrate the file attribute description using file object.

f = open(“file1.txt”, “w+”)
print “Name of the file: “, f.name
print “Closed or not : “, f.closed
print “Opening mode : “, f.mode
print “Softspace flag : “, f.softspace

Output:
Name of the file: file1.txt
Closed or not: False
Opening mode: w+
Softspace flag: 0

The close() Method
The function close() of a file object flushes, if there is any unwritten information and closes
the file object when there is no more writing is can be done. Python closes a file automatically when
the reference object of a file is reassigned with another file. It is a good practice to use the close ()
method to close a file. The syntax of close () function is given below.
5.4 Problem Solving and Python Programming

Syntax
fileObject.close();

The program to perform the open and close operations of a file.


f = open (“file1.txt”, “w+”)
print “Name of the file: “, f.name
# close opened file
f.close()

Output:
Name of the file: file1.txt

Reading and Writing Files


Python provides read () and write ()  methods to read and write files through file object
respectively.

The write() Method
The write() method is used to write any string to a file which is opened. Python strings can
have binary data and not just text. The write() method does not add a newline character (‘\n’) to the
end of the string. The syntax for write() function is shown below.

Syntax
fileObject.write(string);

The argument passed is the content to be written into the opened file. The following program
illustrates the file write operation.
f = open(“file1.txt”, “wb”)
print f
f.write( “Python is a programming language.\nIt is very flexible\n”);
# Close opened file
f.close()

Output:
open file ‘file1.txt’, mode ‘wb’ at 0xb7eb2410
Python is a programming language.
It is very flexible

The above program creates a file file1.txt and writes the given content in that file and finally
it closes that file. If the file is opened, then it would have content which was written.
Files, Modules, Packages 5.5

If the file already exists, then opening it in write mode erases the old data and starts fresh. If
the file doesn’t exist, then a new one is created.

The write method is used to put data into the file.

For example,
line1 = “Python is a programming language, \n”
f.write (line1)
Here, the file object keeps track of where it is pointing to, so if write function is called again,
it adds the new data to the end of the file. For example,
line2 = “It is very flexible .\n”
f.write (line2)

If no more operations need to be performed, then the file could be closed using file close()
function.
f.close()

The read() Method
The file read() function  reads the file contents from an open file. It is important to note that
Python strings can have binary data in addition to text data. The syntax for file read() is given below.

Syntax
fileObject.read([count]);

The argument passed is the number of bytes to be read from the opened file. This method
starts reading from the beginning of the file and if the argument count is missing, then it tries to read
as much as possible, till the end of file.

Example
To read from the file file1.txt
# Open a file
f=open(“file1.txt”, “w+”)
f.write(“ Python is a programming language”)
f.close()
f = open(“file1.txt”, “r+”)
str = f.read(20);
print “ The string read is : “, str
# Close opened file
f.close()
5.6 Problem Solving and Python Programming

Output:
The string read is : Python is a program

5.1.2 Format operator


The file write() function takes the argument as a string. In order to take other values in a file,
it is important to convert them into strings. The easiest way to do is with str function as follows.

x = 52
f.write (str(x))
Here, the str function converts integer x value as string. An alternative way is to use the
format operator, %. When this is applied to integers, % is considered as the modulus operator. But
when the first operand is a string, % is considered as the format operator.

The first operand is the format string that contains one or more format sequences, to specify
how the second operand is formatted. The result is a string. For example, the format sequence ‘%d’
means that the second operand should be formatted as an integer (d stands for “decimal”): consider
the simple example.
x = 15
print ‘%d’ % x

Output:
15
The result is the string ‘15’, which is not to be confused with the integer value 15. A format
sequence can appear anywhere in the string, so you can embed a value in a sentence:

bugs= 10
print ‘I have spotted %d bugs.’ % bugs

Output:
I have spotted 10 bugs
If there is more than one format sequence in the string, the second argument must be a tuple.
Each format sequence is matched with an element of the tuple, in sequence. The various format
sequences are ‘%d’ to format an integer, ‘%g’ to format a floating-point number and ‘%s’ to format
a string.

print ‘In %d years I have spotted %g %s.’ % (2, 0.3, ‘bugs’)

Output:
In 2 years I have spotted 0.3 bugs.
The number of elements in the tuple has to match the number of format sequences in the
string. The types of the elements have to match the format sequences also.
Files, Modules, Packages 5.7

Example:
print ‘%d %d %d’ % (1, 2)

Output:
Traceback (most recent call last):
File “main.py”, line 1, in
print ‘%d %d %d’ % (1, 2)
TypeError: not enough arguments for format string

Example:
print ‘%d’ % ‘dollars’

Output:
Traceback (most recent call last):
File “main.py”, line 1, in
print ‘%d’ % ‘dollars’
TypeError: %d format: a number is required, not str
In the first example, there are three format sequences and only two elements; in the second,
the format sequence is for integer but the element is string. The format operator is more effective,
however it is difficult to use.

Python File functions:


There are various functions available with the file object.

Method Description
close() Close an open file. It has no effect if the file is already closed.
Separate the underlying binary buffer from the TextIOBase
detach()
and return it.
fileno() Return an integer number (file descriptor) of the file.
flush() Flush the write buffer of the file stream.
isatty() Return True if the file stream is interactive.
Read atmost n characters form the file. Reads till end of file
read(n)
if it is negative or None.
readable() Returns True if the file stream can be read from.
Read and return one line from the file. Reads in at most n
readline(n=-1)
bytes if specified.
Read and return a list of lines from the file. Reads in at most
readlines(n=-1)
n bytes/characters if specified.
5.8 Problem Solving and Python Programming

Change the file position to offset bytes, in reference to from


seek(offset,from=SEEK_SET)
(start, current, end).
seekable() Returns True if the file stream supports random access.
tell() Returns the current file location.
Resize the file stream to size bytes. If size is not specified,
truncate(size=None)
resize to current location.
writable() Returns True if the file stream can be written to.
Write string s to the file and return the number of characters
write(s)
written.
writelines(lines) Write a list of lines to the file.

File Positions
The  tell()  method gives the current object position within the file; In other words, the
next read or write will occur at that many bytes from the beginning of the file. The  seek (offset
[, from])  method modifies the current file position. The  offset  argument specifies the number of
bytes to be moved. The from argument specifies the reference position from where the bytes are to
be moved. If from is set to 0, it means use the beginning of the file as the reference position and 1
means use the current position as the reference position and if it is set to 2 then the end of the file
would be taken as the reference position. The following program explains the functions of tell() and
seek() functions.

# Open a file
f=open(“file1.txt”, “w+”)
f.write(“ Python is a programming language”)
f.close()
f = open(“file1.txt”, “r+”)
str = f.read(20);
print “ The string read is : “, str
# Check current position
pos = f.tell();
print “current file position:”, pos
# reposition pointer at the beginning once again
pos = f.seek(0, 0)
str = f . read (10)
print “ Again the string read is: “, str
# close opened file
f . close()
Files, Modules, Packages 5.9

Output:
The string read is : Python is a program
Current file position : 20
Again the string read is : Python is

Renaming and Deleting Files


Python os module provides methods that enable us to perform file-processing operations
like renaming and deleting a file. To use this module it is necessary to import the module first and
then the related functions can be called.

The rename() Method


The rename() method takes two arguments, the current filename and the new filename.
Syntax:
os.rename(current_file_name, new_file_name)
Example:
Following is the example to rename an existing file file1.txt:
import os
# Rename a file from file1.txt to file2.txt
os.rename( “file1.txt”, “file2.txt” )

The remove() Method
The remove() method can be used to delete files by supplying the name of the file to be
deleted as the argument.

Syntax:
os.remove(file_name)

Example:
Following is the example to delete an existing file file2.txt −
import os
# Delete file file2.txt
os.remove(“file2.txt”)
os.mkdir(“test”)

Program for Mail Merge:


To send the same invitations to many people, the body of the mail does not change. Only
the name (and maybe address) needs to be changed. Mail merge is a process of doing this. Instead
of writing each mail separately, we have a template for body of the mail and a list of names that we
merge together to form all the mails.
5.10 Problem Solving and Python Programming

# Python program to mail merger


# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open(“names.txt”,’r’,encoding = ‘utf-8’) as names_file:
# open body.txt for reading
with open(“body.txt”,’r’,encoding = ‘utf-8’) as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
mail = “Hello “+name+body
# write the mails to individual files
with open(name.strip()+”.txt”,’w’,encoding = ‘utf-8’) as mail_file:
mail_file.write(mail)
In this program all the names are written in separate lines in the file named “names.txt”. The
body of the letter is stored in the file “body.txt”

The two files are opened in reading mode and iterate over each name using a for loop. A
new file with the name “[name].txt” is created, where name is the name of that person. Here, the
strip() method is used to clean up leading and trailing whitespaces (reading a line from the file
also reads the newline ‘\n’ character). Finally, we write the content of the mail into this file using
the write() method.

5.1.3 Command Line Arguments


Command line arguments are what we type at the command line prompt along with the
script name while we try to execute our scripts. Python like most other languages provides this
feature. sys.argv is a list in Python, which contains the command line arguments passed to the script.
We can count the number of arguments using len(sys.argv) function. To use sys.argv, we have to
import the sys module.

import sys
print ‘No. of arguments:’, len(sys.argv)
print ‘Argument List:’,str(sys.argv)
Run the above script as follows:
$ python test.py arg1 arg2 arg3
Files, Modules, Packages 5.11

Output:
Number of arguments: 4
Argument List: [‘test.py’, ‘arg1’,’arg2’,’arg3’]

Filenames and paths


Files are organized into directories (also called “folders”). Every program has a “current
directory”, which is the default directory for most operations. For example, when you open a file for
reading, Python looks for it in the current directory. The os module provides functions for working
with files and directories (“os” stands for “operating system”). os.getcwd () returns the name of the
current directory:
import os
cwd = os.getcwd()
print cwd

Output:
/web/com/1493114533_4353

cwd stands for “current working directory.” The result in this example is /web/
com/1493114533_4353.

A string like cwd that identifies a file is called a path. A relative path starts from the current
directory; an absolute path starts from the topmost directory in the file system. The paths we have
seen so far are simple filenames, so they are relative to the current directory. To find the absolute
path to a file, you can use os.path.abspath:

abs_path=os.path.abspath(‘file1.txt’)
print abs_path

Output:
/web/com/1493114533_4353/file1.txt
os.path.exists checks whether a file or directory exists:

print os.path.exists(‘file1.txt’)

Output:
True

If it exists, os.path.isdir checks whether it’s a directory:

print os.path.isdir(‘file1.txt’)

Output:
False
5.12 Problem Solving and Python Programming

Similarly, os.path.isfile checks whether it’s a file.

os.listdir returns a list of the files (and other directories) in the given directory:

>>> os.listdir(cwd)

[‘file1’, ‘file2’]

To demonstrate these functions, the following example “walks” through a directory, prints
the names of all the files, and calls itself recursively on all the directories.
def walk(dirname):
for name in os.listdir(dirname):
path = os.path.join(dirname, name)
if os.path.isfile(path):
print path
else:
walk(path)
os.path.join takes a directory and a file name and joins them into a complete path.

5.2. ERRORS AND EXCEPTION


5.2.1 Errors
Errors or mistakes in a program are often referred to as bugs. They are almost always the
fault of the programmer. Debugging is the process of finding and eliminating errors. Errors can be
classified into three major groups:

•• Syntax errors
•• Runtime errors
•• Logical errors

Syntax Errors
Syntax errors, also known as parsing errors are identified by Python while parsing the
program. It displays error message and exit without continuing execution process. They are similar
to spelling mistakes or grammar mistakes in normal language like English. Some common Python
syntax errors include:
•• leaving out a keyword
•• putting a keyword in the wrong place
•• leaving out a symbol, such as a colon, comma or brackets
•• misspelling a keyword
•• incorrect indentation
Files, Modules, Packages 5.13

•• empty block
Here are some examples of syntax errors in Python:
a=10
b=20
if a<b
print ‘a is greater’

Error Message:
  File “main.py”, line 3 
    if a<b  
         ^   

SyntaxError: invalid syntax 
The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest
point in the line where the error was detected. The error is caused by (or at least detected at) the
token preceding the arrow: in the example, the error is detected at the if a<b since a colon (‘:’) is
missing before it. File name and line number are printed so you know where to look in case the input
came from a script.
if True:
prnt ‘Hello’

Error Message:
  File “main.py”, line 2    
    prnt ‘Hello’  
               ^     

SyntaxError: invalid syntax
In the above example, the error is detected at prnt ‘Hello’ since print is misspelled.

Logical errors
Logical errors occur due to mistake in program’s logic. Here program runs without any error
messages, but produces an incorrect result. These errors are difficult to fix. Here are some examples
of mistakes which lead to logical errors:
•• using the wrong variable name
•• indenting a block to the wrong level
•• using integer division instead of floating-point division
•• getting operator precedence wrong
•• making a mistake in a boolean expression
•• off-by-one, and other numerical errors
5.14 Problem Solving and Python Programming

Here is an example of logical error in Python:


i=1
fact=0
while i<=5:
fact=fact*i
i=i+1
print ‘Fact:’, fact

Sample Output:
Fact:0
In this example for computing factorial of 5, the obtained output is 0. There are no syntax
errors. The wrong output occurs due to logical error fact=0. To compute factorial, the fact value
must be initialized to 1. As it is assigned as 0, it results in wrong output.

5.2.2 Exceptions
An exception is an error that occurs during execution of a program. It is also called as run
time errors. Some examples of Python runtime errors:
•• division by zero
•• performing an operation on incompatible types
•• using an identifier which has not been defined
•• accessing a list element, dictionary value or object attribute which doesn’t exist
•• trying to access a file which doesn’t exist

An example for run time error is as follows.


print (10/0)
Error Message:
Traceback (most recent call last):  
File “main.py”, line 1, in <module> 
print (10/0)
ZeroDivisionError: integer division or modulo by zero  
Exceptions come in different types, and the type is printed as part of the message: the type
in the example is ZeroDivisionError which occurs due to division by 0. The string printed as the
exception type is the name of the built-in exception that occurred.

Exception refers to unexpected condition in a program. The unusual conditions could be


faults, causing an error which in turn causes the program to fail. The error handling mechanism is
referred to as exception handling. Many programming languages like C++, PHP, Java, Python, and
many others have built-in support for exception handling.
Files, Modules, Packages 5.15

Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong. When these exceptions occur, it stops the current process and passes the
control to corresponding exception handler. If not handled, our program will crash.

Some of the standard exceptions available in Python are listed below.


Exception Name Description
Exception Base class for all exceptions
ArithmeticError Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a numeric
type.
FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place for all
numeric types.
AssertionError Raised in case of failure of the Assert statement
EOFError Raised when there is no input from either the raw_input() or
input() function and the end of file is reached.
ImportError Raised when an import statement fails.
IndexError Raised when an index is not found in a sequence
KeyError Raised when the specified key is not found in the dictionary.
NameError Raised when an identifier is not found in the local or global
namespace
IOError Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that
does not exist.
SyntaxError Raised when there is an error in Python syntax
SystemExit Raised when Python interpreter is quit by using the sys.exit()
function. If not handled in the code, causes the interpreter to exit
TypeError Raised when an operation or function is attempted that is invalid
for the specified data type
ValueError Raised when the built-in function for a data type has the valid type
of arguments, but the arguments have invalid values specified.
RuntimeError Raised when a generated error does not fall into any category

Handling Exceptions
The simplest way to handle exceptions is with a “try-except” block. Exceptions that are
caught in try blocks are handled in except blocks. The exception handling process in Python is
shown in Figure.5.1. If an error is encountered, a try block code execution is stopped and control
transferred down to except block.
5.16 Problem Solving and Python Programming

Try Raise Except

Exception may Raise the Catch if


occur Exception exception occurs

Figure 5.1. Exception Handling

Syntax:
try:
# statements
break
except ErrorName:
# handler code

The try statement works as follows.


•• First, the try clause (the statement(s) between the try and except keywords) is executed.
•• If no exception occurs, the except clause is skipped and execution of the try statement
is finished.
•• If an exception occurs during execution of the try clause, the rest of the clause is skipped.
Then if its type matches the exception named after the except keyword, the except
clause is executed, and then execution continues after the try statement.
•• If an exception occurs which does not match the exception named in the except clause, it
is passed on to outer try statements; if no handler is found, it is an unhandled exception
and execution stops with a message.
A simple example to handle divide by zero error is as follows.

(x,y) = (5,0)
try:
z = x/y
except ZeroDivisionError:
print “divide by zero”

Sample Output:
divide by zero
To display built-in error message of exception, you could have :
(x,y) = (5,0)
try:
z = x/y
Files, Modules, Packages 5.17

except ZeroDivisionError as e:
z = e # representation: “<exceptions.ZeroDivisionError instance at 0x817426c>”
print z # output: “integer division or modulo by zero”

Sample Output:
integer division or modulo by zero 

A try statement may have more than one except clause, to specify handlers for different
exceptions. If an exception occurs, Python will check each except clause from the top down to see
if the exception type matches. If none of the except clauses match, the exception will be considered
unhandled, and your program will crash:

Syntax:
try:
# statements
break
except ErrorName1:
# handler code
except ErrorName2:
# handler code
A simple example to handle multiple exceptions is as follows.

try:
dividend = int(input(“Please enter the dividend: “))
divisor = int(input(“Please enter the divisor: “))
print(“%d / %d = %f” % (dividend, divisor, dividend/divisor))
except ValueError:
print(“The divisor and dividend have to be numbers!”)
except ZeroDivisionError:
print(“The dividend may not be zero!”)

Sample input/output (successful):


Please enter the dividend: 10                                                                                                 
Please enter the divisor: 2                                                                                                   
10 / 2 = 5.000000     
5.18 Problem Solving and Python Programming

Sample input/output (unsuccessful-divide by zero error):


Please enter the dividend: 10   
Please enter the divisor: 0      
The dividend may not be zero! 

Sample input/output (unsuccessful-value error):


Please enter the dividend: ‘s’   
The divisor and dividend have to be numbers!  

An except clause may name multiple exceptions as a parenthesized tuple, for example:
... except (RuntimeError, TypeError, NameError):

... #handler code

Example:
try:
dividend = int(input(“Please enter the dividend: “))
divisor = int(input(“Please enter the divisor: “))
print(“%d / %d = %f” % (dividend, divisor, dividend/divisor))
except(ValueError, ZeroDivisionError):
print(“Oops, something went wrong!”)

Sample Input/Output:
Please enter the dividend: 10  
Please enter the divisor: 0    
Oops, something went wrong! 
To catch all types of exceptions using single except clause, simply mention except keyword
without specifying error name. It is shown in following example.
try:
dividend = int(input(“Please enter the dividend: “))
divisor = int(input(“Please enter the divisor: “))
print(“%d / %d = %f” % (dividend, divisor, dividend/divisor))
except:
print(“Oops, something went wrong!”)

Raising Exceptions
The raise statement initiates a new exception. It allows the programmer to force a specified
exception to occur. The raise statement does two things: it creates an exception object, and
Files, Modules, Packages 5.19

immediately leaves the expected program execution sequence to search the enclosing try statements
for a matching except clause. It is commonly used for raising user defined exceptions. Two forms
of the raise statement are:

Syntax:
raise ExceptionClass(value)
raise Exception

Example:
try:
raise NameError
except NameError:
print(‘Error’)

Sample Output:
Error
raise without any arguments is a special use of python syntax. It means get the exception
and re-raise it. The process is called as reraise. If no expressions are present, raise re-raises the last
exception that was active in the current scope.

Example:
try:
raise NameError
except NameError:
print(‘Error’)
raise

Sample Output:
Error
Traceback (most recent call last):  
File “main.py”, line 2, in <module> 
raise NameError(‘Hi’) 
NameError: Hi     
In the example, raise statement inside except clause allows you to re-raise the exception
NameError.

The else and finally statements


Two clauses that can be added optionally to try-except block are else and finally. else will be
executed only if the try clause doesn’t raise an exception:
5.20 Problem Solving and Python Programming

try:
age = int(input(“Please enter your age: “))
except ValueError:
print(“Hey, that wasn’t a number!”)
else:
print(“I see that you are %d years old.” % age)

Sample input/output:
Please enter your age: 10  
I see that you are 10 years old.   
Please enter your age: ‘a’   
Hey, that wasn’t a number! 
In addition to using except block after the try block, you can also use the finally block. The
code in the finally block will be executed regardless of whether an exception occurs and even if we
exit the block using break, continue, or return.

try:
age = int(input(“Please enter your age: “))
except ValueError:
print(“Hey, that wasn’t a number!”)
else:
print(“I see that you are %d years old.” % age)
finally:
print(“Goodbye!”)

Sample input/output:
Please enter your age: 20 
I see that you are 20 years old.  
Goodbye!    

5.2.2.1 User-defined Exceptions


Python allows the user to create their custom exceptions by creating a new class. This
exception class has to be derived, either directly or indirectly, from Exception class.

# define Python user-defined exceptions


class Error(Exception):
“””Base class for other exceptions”””
Files, Modules, Packages 5.21

pass # null operation


class PosError(Error):
“””Raised when the input value is positive”””
pass
class NegError(Error):
“””Raised when the input value is negative”””
pass
# our main program
number = 0
while True:
try:
i_num = int(input(“Enter a number: “))
if i_num < number:
raise NegError
elif i_num > number:
raise PosError
break
except PosError:
print(“This value is positive!”)
print()
except NegError:
print(“This value is negative!”)
print()

Sample input/output:
Enter a number: 12
This value is positive!
In the example, the user defined exception class Error is derived from built-in class
Exception. It handles two user defined exceptions: PosError, raised when input value is positive
and NegError, raised when input value is negative. The pass keyword indicates null block. The
main program reads user input and compares input value with 0. If input>0, the exception PosError
is raised using raise keyword else the exception NegError is raised.

5.3 MODULES
A Python module is a file that consists of Python code. It allows us to logically arrange
related code and makes the code easier to understand and use. It defines functions, classes and
variables.
5.22 Problem Solving and Python Programming

Python has many useful functions and resources in modules. Functions such as abs() and
round() from __builtin__ module are always directly accessible in every Python code. But, the
programmer must explicitly import other functions from the modules in which they are defined.

import statement
An import statement is used to import Python module in some Python source file. 

The syntax is:

import module1[, module2[,... modulen]

When an ‘import’ statement is encountered by the interpreter, the corresponding module(s)


is imported if it is available in the search path.

Example:
import math

To use a resource from a module, the following syntax is used:


modulename.resourcename

For example, math is a built-in module that offers several built-in functions for carrying out
basic mathematical operations. The following code imports math module and lists a directory of its
resources:
import math
print dir(math)
Output:
[‘__doc__’, ‘__file__’, ‘__name__’, ‘__package__’, ‘acos’, ‘acosh’, ‘asin’, ‘asinh’,
‘atan’, ‘atan2’, ‘atanh’, ‘ceil’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’, ‘e’, ‘erf’, ‘erfc’,
‘exp’, ‘expm1’, ‘fabs’, ‘factorial’, ‘floor’, ‘fmod’, ‘frexp’, ‘fsum’, ‘gamma’,
‘hypot’, ‘isinf’, ‘isnan’, ‘ldexp’, ‘lgamma’, ‘log’, ‘log10’, ‘log1p’, ‘modf’, ‘pi’,
‘pow’, ‘radians’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘trunc’]
The usage of some built-in functions of math module is shown in the following code along
with its output:
import math # Import built-in module math
print math.floor(6.9)
print math.ceil(6.9)
print math.pow(3,4)
Output:
6.0
7.0
81.0
Files, Modules, Packages 5.23

The following table gives description about a few modules of Python:


Table 5.1: Python modules and their description
Module Description
cmath Mathematical operations using complex numbers
copy Shallow copy and deep copy operations
datetime Date and time
fileinput Loop over standard input or list of files
keyword Testing whether a given string is a keyword
linecache Accessing individual lines of text files randomly
math Basic mathematical operations
modulefinder Finding modules
numbers Abstract base classes for numerals
operator Functions analogous to basic operators
py_compile Compiling Python source code to generate byte code
statistics Statistical operations
string String operations

5.3.1 Writing modules


Any Python source file can be imported as a module into another Python source file. For
example, consider the following code named as support.py, which is a Python source file defining
two functions add() and display().

support.py
def add( a, b ):
print ‘Result is ‘, a+b
return
def display(p):
print ‘Welcome, ‘,p
return
This support.py file can be imported as a module in another Python source file and its
functions can be called from the new file as shown in the following code:
import support # Import module support
support.add(3,4) # calling add() of support module with two integer values
support.add(3.5,4.7) # calling add() of support module with two real values
support.add(‘a’,’b’) # calling add() of support module with two character values
support.add(‘Ram’,’Kumar’) # calling add() of support module with two string values
support.display(‘Ram’) # calling display() of support module with a string value
5.24 Problem Solving and Python Programming

When this code is executed, the following output is produced:


Result is 7
Result is 8.2
Result is ab
Result is RamKumar
Welcome, Ram

from...import Statement
It allows us to import specific attributes from a module into the current namespace.

Syntax:
from modulename import name1[, name2[, ... nameN]]

The first statement of the following code does not import the entire module support into the
current namespace; it just introduces the item add from the module support into the global symbol
table of the importing module. Hence, a call to display() function generates an error as shown in the
output.
from support import add # Import module support
add(3,4) # calling add() of support module with two integer values
add(3.5,4.7) # calling add() of support module with two real values
add(‘a’,’b’) # calling add() of support module with two character values
add(‘Ram’,’Kumar’) # calling add() of support module with two string values
display(‘Ram’) # calling display() of support module with a string value

Output:
Result is 7
Result is 8.2
Result is ab
Result is RamKumar
Traceback (most recent call last):
File “main.py”, line 8, in
display(‘Ram’) # calling display() of support module with a string value
NameError: name ‘display’ is not defined
Files, Modules, Packages 5.25

from...import * Statement:
It allows us to import all names from a module into the current namespace.

Syntax:
from modulename import *

Sample Code:
from support import * # Import module support
add(3,4) # calling add() of support module with two integer values
add(3.5,4.7) # calling add() of support module with two real values
add(‘a’,’b’) # calling add() of support module with two character values
add(‘Ram’,’Kumar’) # calling add() of support module with two string values
display(‘Ram’) # calling display() of support module with a string value

Sample Output:
Result is 7
Result is 8.2
Result is ab
Result is RamKumar
Welcome, Ram

Programs that will be imported as modules often use the following expression:
if __name__ == ‘__main__’:
# test code

Here, __name__ is a built-in variable and is set when the program starts execution. If the
program runs as a script, __name__ has the value __main__ and the test code is executed. Else, the
test code is skipped.

Sample Code:
from support import * # Import module support
if __name__ == ‘__main__’: # add() and display() are called only if this pgm runs as
a script.
add(3,4)
display(‘Ram’)

Sample Output:
Result is 7
Welcome, Ram
reload()
5.26 Problem Solving and Python Programming

When the module is already imported into a script, the module is not re-read eventhough it
is modified. The code of a module is executed only once. To reload the previously imported module
again, the reload() function can be used.

Syntax:
reload(modulename)

Suppose we have the following code in a module named my_module.

print(“Welcome”)

Now, examine the following execution sequence:


>>> import my_module
Welcome
>>> import my_module
>>> import my_module
Here, the code is executed only once since the module was imported only once. If the
module is subsequently changed, it has to be reloaded. For this reloading, one of the approaches is
to restart the interpreter. But this does not help much. So, we can employ reload() inside the imp
module as shown:
>>> import imp
>>> import my_module
Welcome
>>> import my_module
>>> imp.reload(my_module)
Welcome
<module ‘my_module’ from ‘.\\my_module.py’>

5.3.2 Locating Modules


When a module is imported, Python interpreter searches for the module in the following
sequence:

(1) The current directory.


(2) If the module is not found in the current directory, each directory in the shell variable
PYTHONPATH is searched.
(3) At last, Python checks the installation-dependant default directory.
The module search path is stored in sys module as sys.path variable. This variable contains
the current directory, PYTHONPATH, and the installation-dependent default.
Files, Modules, Packages 5.27

5.4 PACKAGES
When we have a large number of Python modules, they can be organized into
packages such that similar modules are placed in one package and different modules are
placed in different packages. A package is a hierarchical file directory structure that defines a
single Python application environment that consists of modules, sub-packages, sub-subpackages,
and so on. In another words, it is a collection of modules. When a package is imported, Python
explores in list of directories on sys.path for the package subdirectory.

5.4.1 Steps to Create a Python Package


(1) Create a directory and name it with a package name.
(2) Keep subdirectories (subpackages) and modules in it.
(3) Create  __init__.py  file in the directory
This __init__.py file can be left empty but we generally place the initialization code with
import statements to import resources from a newly created package. This file is necessary since
Python will know that this directory is a Python package directory other than an ordinary directory.

Example:
Assume we are creating a package named Animals with some subpackages as shown in
Figure.5.2.
Animals
(Package)

_init_.py Mammals Birds


(Module) (Sub-Package) (Sub-Package)

_init_.py _init_.py
(Module) (Module)

create.py create.py
(Module) (Module)

print.py display.py
(Module) (Module)

Figure 5.2. Organization of packages and modules


Modules are imported from packages using dot (.) operator.

Method 1:
Consider, we import the display.py  module in the above example. It is accomplished by the
following statement.
5.28 Problem Solving and Python Programming

import Animals.Birds.display

Now if this display.py module contains a function named displayByName(), we must use


the following statement with full name to reference it.
Animals.Birds.display.displayByName()

Method 2:
On another way, we can import display.py module alone as follows:
from Animals.Birds import display

Then, we can call displayByName() function simply as shown in the following statement:
display.displayByName()

Method 3:
In the following statement, the required function alone is imported from a module within a
package:
from Animals.Birds.display import displayByName

Now, this function is called directly:


displayByName()

Though this method is simple, usage of full  namespace  qualifier avoids confusion and
prevents two similar identifier names from colliding.

In the above example, __init__.py of Animals package contains the following code:
from Mammals import Mammals
from Birds import Birds

In python, module is a single Python file and package is a directory of Python modules
containing an additional  __init__.py  file. Packages can be nested to any depth, but the
corresponding directories should include their own __init__.py file.

5.5 ILLUSTRATIVE PROGRAMS


5.5.1 Python program to handle exception when file open fails
try:
   fob = open(“test”, “r”) # open file in read mode
   fob.write(“It’s my test file to verify exception handling in Python!!”)
except IOError:
   print “Error: can\’t find the file or read data” # Exception occurs
else:
Files, Modules, Packages 5.29

   print “Write operation is performed successfully on the file” # no Exception


Error:
Error: can’t find the file or read data

5.5.2 Python program to raise an exception when the user input is negative
try:
a = int(input(“Enter a positive integer value: “))
if a <= 0:
raise ValueError(“This is not a positive number!!”)
except ValueError as ve:
print(ve)

Sample input:
Enter a positive integer value: -1
Error:
This is not a positive number!!

5.5.3 Python program to count number of words in a file


try:
filename = ‘GettysburgAddress.txt’ # specify your input file name
textfile = open(filename, ‘r’)
print(“The number of words are: “ + len(textfile.split(“ “)))
textfile.close()
except IOError:
print ‘Cannot open file %s for reading’ % filename
import sys
sys.exit(0)
# Exception is raised
Sample Output: if no is negative

The number of words are: 20

5.5.4 Python program to count the frequency of words in a text file


file=open(“test.txt”,”r+”)
wordcount={} # define a dictionary that holds words its count
for word in file.read().split(): # for loop iterates through each word is the file
if word not in wordcount:
5.30 Problem Solving and Python Programming

wordcount[word] = 1
else:
wordcount[word] += 1
for k,v in wordcount.items():
print k, v
file.close()

Sample Output:
This 1
program 2
example 1
Python 2

5.5.5 Python program to copy a content of one file to another


Program 1:
rfile=open(‘/testfile.txt’, ‘r’) try: # open file is read mode
      reading_file=rfile.read()
      wfile=open(‘/testfile2.txt’, ‘w’) # open file is write mode
      try:
           wfile.write(reading_file) # write into file
      finally:
           wfile.close()
finally:
      rfile.close()

Program 2:
with open(“in.txt”) as f:
with open(“out.txt”, “w”) as f1:
for line in f:
if “ROW” in line:
f1.write(line)

Program 3:
# The shutil module offers a number of high-level operations on files and collections
of files
from shutil import copyfile
copyfile(‘test.py’, ‘abc.py’) # copy content of test.py to abc.py
Files, Modules, Packages 5.31

5.6.6 Python program to append text to a file and display the text
def file_read(fname):
with open(fname, “w”) as myfile:
myfile.write(“Python Exercises\n”)
myfile.write(“Java Exercises”)
txt = open(fname)
print(txt.read())
file_read(‘abc.txt’)

Sample Output:
Python Exercises
Java Exercises

Python program to count the number of lines in a text file


def file_lengthy(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
print(“Number of lines in the file: “,file_lengthy(“test.txt”))
In this example, f is the file object. enumerate(f) iterate over lines of the file. So each time
through the loop i gets assigned a line number, and l gets assigned the corresponding line from the
file.

Random access file - Python program to read a random line from a file.
A random-access data file enables you to read or write information anywhere in the file.
You can use seek()  method to set the file marker position and  tell() method to get the current
position of the file marker. In a sequential-access file, you can only read and write information
sequentially, starting from the beginning of the file.
f=open(‘Python_source\\test.txt’,’w’) 
f.write(‘DearChanna ‘) 
f.seek(4) #move file pointer to 4th position from beginning of file
f.write(‘ Mr.Channa’) 
f.close() 
f=open(‘Python_source\\test.txt’,’r’) 
f.read() 

Sample Output:
Dear Mr.Channa
5.32 Problem Solving and Python Programming

Program that asks the user to input customer information, call writetofile method to
write data to the file and call getall method to retrieve customer information from file.
#write data to file
def writetofile(Name,Email=’’,Tel=’’,Address=’’): 
        try: 
                f=open(r’customerlist.txt’,’a’) 
                f.write(Name+’:’+Email+’:’+Tel+’:’+Address+’\n’) 
        except Exception:’Print error in writing to file...’ 
        finally: 
                f.flush() 
                f.close()
#Get all customers’information and display
def getall(): 
        f=open(r’customerlist.txt’,’r’)#open file for reading 
        content=f.readlines()#read all lines 
        f.close() 
        return content
def add(): 
        Name=raw_input(‘Name:’) 
        Email=raw_input(‘Email:’) 
        Tel=raw_input(‘Tel:’) 
        Address=raw_input(‘Address:’) 
        writetofile(Name,Email,Tel,Address) 
#main program
add()
print getall()

With reference to previous program, write a method to search for a customer by name.
#Search customer by name. If match is found, it returns the position of the name else
returns -1.
def search(Name): 
        global flag#declare global variable 
        try: 
           f=open(r’customerlist.txt’,’r’)#open file for reading 
Files, Modules, Packages 5.33

           f.seek(0) 
           content=f.readline() 
           while content!=’’: 
                if content.find(Name)!=-1: 
                    print content 
                     flag=1 
return int(f.tell())-int(len(content)+1) # return the position of the matched name
               else: 
                   content=f.readline() 
                                flag=0 
        except Exception:print ‘Error in reading file...’ 
        finally: 
                 f.close() 
                 if flag==0: 
                         print ‘Not found’ #Inform the use if the record does not exist 
                         return -1 # The record not found-->return -1 

Using previous search method, write a program to delete a customer name from file.
#delete customer’s information by name              
def delete(Name): 
        print search(Name) 
        p=search(Name) # returns position of given customer name
        print “x=”,p 
        if p!=-1: #Make sure the record exists 
                st=getall() #retrieve content about cutomer
                f=open(r’customerlist.txt’,’w’)#open file for writing 
                f.writelines(st) 
                f.seek(p) 
                f.write(‘*****’)#write 5 starts to override the 5 characters of the name to be
deleted 
        else: 
                print ‘No record to delete’#Inform the use if the record does not exist
         f.close() 
PROBLEM SOLVING AND PYTHON
PROGRAMMING LABORATORY

TABLE OF CONTENTS
Ex.
DATE NAME OF THE EXPERIMENT PAGE No. MARKS SIGNATURE
No.
1. Compute the GCD of two numbers. App-A.1
2. Find the square root of a number App-A.2
(Newton’s method)
3. Exponentiation (power of a number) App-A.3
4. Linear search and Binary search App-A.4
5. First n prime numbers App-A.6
6. Find the maximum of a list of App-A.7
numbers
7. Selection sort, Insertion sort App-A.9
8. Removing all the duplicate elements App-A.12
in a list
9. Merge sort, Quick sort App-A.14
10. Multiply Matrices App-A.18
11. Programs that take command line App-A.20
arguments (word count)
12. Find the most frequent words in a App-A.21
text read from a file
APPENDIX - A

LAB PROGRAMS

Ex.No. 1 Compute the GCD of two numbers.


Date:

Aim
To write an python program to find the Greatest Common Divisor of any two positive
integers.

Algorithm
Program
a=int(input("x value="))
b=int(input("y value="))
def gcd(x, y):
gcd = 1

if x % y == 0:
return y

for k in range(int(y / 2), 0, -1):


if x % k == 0 and y % k == 0:
gcd = k
break
print("The Greatest Common Divisor of {0} and {1} is".format(x,y),gcd)
gcd(a,b)
Output
x value=90
y value=100
The Greatest Common Divisor of 90 and 100 is 10

Result:
Thus the above program was executed successfully and output was verified.
App-A.2 Problem Solving and Python Programming

Ex.No. 2 Find the square root of a number


Date:

Aim
To write an python program to find the squre root of a given positive integer.

Algorithm
Program
while True:
print("Enter 'x' for exit.")
num = input("Enter a number: ")
if num == 'x':
break
else:
number = float(num)
number_sqrt = number ** 0.5
print("Square Root of %0.3f is %0.3f" %(number, number_sqrt))

Output:
Enter 'x' for exit.
Enter a number: 3
Square Root of 3.000 is 1.732
Enter 'x' for exit.
Enter a number: 16
Square Root of 16.000 is 4.000
Enter 'x' for exit.
Enter a number: x

Result:
Thus the above program was executed successfully and output was verified.
Appendix -A Lab Programs App-A.3

Ex.No. 3 Exponentiation (power of a number)


Date:

Aim
To write an python program to find the exponentiation of a given positive integer.

Algorithm
Program
import math
a=float(input("Enter a value"))
print("The exponential value of {0} is ".format(a),math.exp(a))

Output
Enter a value100.12
The exponential value of 100.12 is 3.03084361407e+43

Result:
Thus the above program was executed successfully and output was verified.
App-A.4 Problem Solving and Python Programming

Ex.No. 4 Linear search and Binary search


Date:

Aim
To write an python program to perform linear search and binary search.

Algorithm
Program
Linear Search
def linearSearch(myItem,myList):
found = False
position = 0
while position < len(myList) and not found:
if myList[position] == myItem:
found = True
position = position +1
return found

if __name__=="__main__":
shopping=["Apple","Banana","Orange","Guvava","Pienapple","Bread","Milk"]
item = input("Enter your item to search: ")
isitFound = linearSearch(item,shopping)
if isitFound:
print("Your item is in the list")
else:
print("Sorry your item not in the list")

Output:
Enter your item to search: Apple
Your item is in the list
Enter your item to search: Butter
Sorry your item not in the list

Binary Search
def binarySearch(myItem,myList):
found = False
Appendix -A Lab Programs App-A.5

bottom = 0
top = len(myList) - 1
while bottom <= top and not found:
middle = (bottom+top)//2
if myList[middle] == myItem:
found = True
elif myList[middle] < myItem:
bottom = middle + 1
else:
top = middle-1
return found

if __name__=="__main__":
numberList=[1,3,4,8,69,45,32,46,78,20,25,46,10,75,36,99,100]
number = int(input("Enter your number to search: "))
isitFound = binarySearch(number,numberList)
if isitFound:
print("The entered number {0} is in the list".format(number))
else:
print("The entered number {0} is not in the list".format(number))

Output:
Enter your number to search: 45
The entered number 45 is in the list
Enter your number to search: 1000
The entered number 1000 is not in the list

Result
Thus the above program was executed successfully and output was verified.
App-A.6 Problem Solving and Python Programming

Ex.No. 5 First n prime numbers


Date:
Aim
To write an python program to find the first n prime numbers
Algorithm
Program
i=1
x = int(input("Enter the number:"))
for k in range (1, (x+1), 1):
c=0
for j in range (1, (i+1), 1):
a = i%j
if (a==0):
c = c+1
if (c==2):
print (i)
else:
k = k-1
i=i+1

Output
Enter the number:50
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47

Result
Thus the above program was executed successfully and output was verified.
Appendix -A Lab Programs App-A.7

Ex.No. 6 Find the maximum of a list of numbers


Date:

Aim
To write an python program to find the maximum of a list of numbers.

Algorithm
Program
def highestNumber(l):
myMax = l[0]
for num in l:
if myMax < num:
myMax = num
return myMax

list=[]
while True:
print("Enter '-1' for exit.")
list1=int(input("Enter a number: "))
if list1 == -1:
break
else:
list.append(list1)

print("The created list is \n",list)


maxelement = highestNumber (list)
print("The maximum value in the list is {0}".format(maxelement))
Output
Enter '-1' for exit.
Enter a number: 23
Enter '-1' for exit.
Enter a number: 600
Enter '-1' for exit.
Enter a number: 48
Enter '-1' for exit.
Enter a number: 60
App-A.8 Problem Solving and Python Programming

Enter '-1' for exit.


Enter a number: 200
Enter '-1' for exit.
Enter a number: 15
Enter '-1' for exit.
Enter a number: 1000
Enter '-1' for exit.
Enter a number: -1
The created list is
[23, 600, 48, 60, 200, 15, 1000]
The maximum value in the list is 1000

Result
Thus the above program was executed successfully and output was verified.
Appendix -A Lab Programs App-A.9

Ex.No. 7 Implementation of Selection sort and Insertion sort


Date:

Aim
To write an python program to perform Selection sort and Insertion sort.

Algorithm
Program
Selection Sort
def selectionSort(nlist):
for fillslot in range(len(nlist)-1,0,-1):
maxpos=0
for location in range(1,fillslot+1):
if nlist[location]>nlist[maxpos]:
maxpos = location
temp = nlist[fillslot]
nlist[fillslot] = nlist[maxpos]
nlist[maxpos] = temp
nlist = []
while True:
print("Enter '-1' for exit.")
list1=int(input("Enter a number: "))
if list1 == -1:
break
else:
nlist.append(list1)
print("The created list is \n",nlist)
selectionSort(nlist)
print("The sorted elements are",nlist)

Output
Enter '-1' for exit.
Enter a number: 2
Enter '-1' for exit.
App-A.10 Problem Solving and Python Programming

Enter a number: 3
Enter '-1' for exit.
Enter a number: 4
Enter '-1' for exit.
Enter a number: 69
Enter '-1' for exit.
Enter a number: 100
Enter '-1' for exit.
Enter a number: 65
Enter '-1' for exit.
Enter a number: 78
Enter '-1' for exit.
Enter a number: 60
Enter '-1' for exit.
Enter a number: -1
The created list is
[2, 3, 4, 69, 100, 65, 78, 60]
The sorted elements are [2, 3, 4, 60, 65, 69, 78, 100]

Insertion sort
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = []
while True:
print("Enter '-1' for exit.")
list1=int(input("Enter a number: "))
if list1 == -1:
Appendix -A Lab Programs App-A.11

break
else:
alist.append(list1)
print("The created list is \n",alist)
insertionSort(alist)
print("The sorted elements are",alist)

Output
Enter '-1' for exit.
Enter a number: 23
Enter '-1' for exit.
Enter a number: 10
Enter '-1' for exit.
Enter a number: 60
Enter '-1' for exit.
Enter a number: 1
Enter '-1' for exit.
Enter a number: 8
Enter '-1' for exit.
Enter a number: 3
Enter '-1' for exit.
Enter a number: -1
The created list is
[23, 10, 60, 1, 8, 3]
The sorted elements are [1, 3, 8, 10, 23, 60]

Result
Thus the above program was executed successfully and output was verified.
App-A.12 Problem Solving and Python Programming

Ex.No. 8 Removing all the duplicate elements in a list


Date:

Aim
To write an python program to remove all the duplicate elements in a list.

Algorithm
Program
def removeDuplicate(alist):
print("Before eliminating duplicate entries in the list",alist)
rlist=list(set(alist))
print("After eliminating duplicate entries in the list",rlist)
alist = []
while True:
print("Enter 'x' for exit.")
list1=input("Enter a number: ")
if list1 == 'x':
break
else:
alist.append(list1)
print("The created list is \n",alist)
removeDuplicate(alist)

Output
Enter 'x' for exit.
Enter a number: 5
Enter 'x' for exit.
Enter a number: 6
Enter 'x' for exit.
Enter a number: 5
Enter 'x' for exit.
Enter a number: 2
Enter 'x' for exit.
Enter a number: 2
Appendix -A Lab Programs App-A.13

Enter 'x' for exit.


Enter a number: x
The created list is
['5', '6', '5', '2', '2']
Before eliminating duplicate entries in the list ['5', '6', '5', '2', '2']
After eliminating duplicate entries in the list ['2', '5', '6']

Result
Thus the above program was executed successfully and output was verified.
App-A.14 Problem Solving and Python Programming

Ex.No. 9 Implementation of Merge sort and Quick sort


Date:

Aim
To write an python program to implement merge sort and quick sort.

Algorithm
Program
Merge Sort
def merge(a,b):
""" Function to merge two arrays """
c = []
while len(a) != 0 and len(b) != 0:
if a[0] < b[0]:
c.append(a[0])
a.remove(a[0])
else:
c.append(b[0])
b.remove(b[0])
if len(a) == 0:
c += b
else:
c += a
return c

def mergeSort(alist):
""" Function to sort an array using merge sort algorithm """
if len(alist) == 0 or len(alist) == 1:
return alist
else:
middle = len(alist)//2
a = mergeSort(alist[:middle])
b = mergeSort(alist[middle:])
return merge(a,b)

alist = []
Appendix -A Lab Programs App-A.15

while True:
print("Enter '-1' for exit.")
list1=int(input("Enter a number: "),10)
if list1 == -1:
break
else:
alist.append(list1)

print("The created list is \n",alist)


msort=mergeSort(alist)
print("After doing merge sort \n",msort)

Output
Enter '-1' for exit.
Enter a number: 36
Enter '-1' for exit.
Enter a number: 62
Enter '-1' for exit.
Enter a number: 89
Enter '-1' for exit.
Enter a number: 1
Enter '-1' for exit.
Enter a number: 325
Enter '-1' for exit.
Enter a number: 63
Enter '-1' for exit.
Enter a number: 55
Enter '-1' for exit.
Enter a number: 87
Enter '-1' for exit.
Enter a number: -1
The created list is
[36, 62, 89, 1, 325, 63, 55, 87]
After doing merge sort
[1, 36, 55, 62, 63, 87, 89, 325]
App-A.16 Problem Solving and Python Programming

Quick Sort
def quickSort(myList, start, end):
if start < end:
# partition the list
pivot = partition(myList, start, end)
# sort both halves
quickSort(myList, start, pivot-1)
quickSort(myList, pivot+1, end)
return myList

def partition(myList, start, end):


pivot = myList[start]
left = start+1
right = end
done = False
while not done:
while left <= right and myList[left] <= pivot:
left = left + 1
while myList[right] >= pivot and right >=left:
right = right -1
if right < left:
done= True
else:
# swap places
temp=myList[left]
myList[left]=myList[right]
myList[right]=temp
# swap start with myList[right]
temp=myList[start]
myList[start]=myList[right]
myList[right]=temp
return right

alist = []
while True:
print("Enter '-1' for exit.")
Appendix -A Lab Programs App-A.17

list1=int(input("Enter a number: "))


if list1 == -1:
break
else:
alist.append(list1)
print("The created list is \n",alist)
qsort=quickSort(alist,0,len(alist)-1)
print("After doing merge sort \n",qsort)

Output
Enter '-1' for exit.
Enter a number: 23
Enter '-1' for exit.
Enter a number: 56
Enter '-1' for exit.
Enter a number: 41
Enter '-1' for exit.
Enter a number: 20
Enter '-1' for exit.
Enter a number: 63
Enter '-1' for exit.
Enter a number: 45
Enter '-1' for exit.
Enter a number: 10
Enter '-1' for exit.
Enter a number: 1
Enter '-1' for exit.
Enter a number: 3
Enter '-1' for exit.
Enter a number: -1
The created list is
[23, 56, 41, 20, 63, 45, 10, 1, 3]
After doing merge sort
[1, 3, 10, 20, 23, 41, 45, 56, 63]

Result
Thus the above program was executed successfully and output was verified.
App-A.18 Problem Solving and Python Programming

Ex.No. 10 Implementation of Multiplying Matrices


Date:

Aim
To write an python program to implement multiplication of N X N Matrices.

Algorithm
Program
matrixA = []
matrixB = []
print("Enter the value of N for N x N:")
N = int(input())
print("Enter the elements of matrix A:")
for i in range(N):
matrixA.append(input().split())
print("Enter the elements of matrix B:")
for i in range(N):
matrixB.append(input().split())

# multiply two matrices


print("Resultant matrix is: (matrixA * matrixB)")
for i in range(N):
for j in range(N):
sum=0
for k in range(N):
sum = sum + int(matrixA[i][k]) * int(matrixB[k][j])
print(sum)
print(" ")
Output
Enter the value of N for N x N:
2
Enter the elements of matrix A:
12
34
Appendix -A Lab Programs App-A.19

Enter the elements of matrix B:


12
34
Resultant matrix is: (matrixA * matrixB)
7
10

15
22

Result
Thus the above program was executed successfully and output was verified.
App-A.20 Problem Solving and Python Programming

Ex.No. 11 Implement a Programs that take command line arguments


(word count)
Date:

Aim
To write an python program to implement a program that take command line arguments.

Algorithm
Program – Can able to execute in ubuntu
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
Output
vctw@vctwcsevb:~/Desktop/cmdline$ python cmdlinearg.py 1

vctw@vctwcsevb:~/Desktop/cmdline$ python cmdlinearg.py 1 2 3 4 –sum

10

Result
Thus the above program was executed successfully and output was verified.
Appendix -A Lab Programs App-A.21

Ex.No. 12 Implement a python program find the most frequent words in a


text read from a file
Date:

Aim
To write an python program to implement a program to find the most frequent words in a
text read from a file.

Algorithm
Program
from string import punctuation
from operator import itemgetter
wordsCount=0
words = {}
words_gen = (word.strip(punctuation).lower() for line in open("D:\\S\\test.txt")
for word in line.split())
for word in words_gen:
words[word] = words.get(word, 0) + 1
wordsCount +=1
top_words = sorted(words.items(), key=itemgetter(1), reverse=True)[:wordsCount]
print("Number of Words in the given text File: ",wordsCount)
print("Words frequencies are: ")
print("=======================")
for word, frequency in top_words:
print("%s: %d" % (word, frequency))

Output
Number of Words in the given text File: 31
Words frequencies are:
=======================
and: 4
a: 2
programming: 2
features: 1
dynamic: 1
App-A.22 Problem Solving and Python Programming

it: 1
library: 1
including: 1
management: 1
system: 1
imperative: 1
memory: 1
has: 1
supports: 1
styles: 1
multiple: 1
python: 1
comprehensive: 1
functional: 1
standard: 1
paradigms: 1
type: 1
large: 1
object-oriented: 1
automatic: 1
procedural: 1

Result
Thus the above program was executed successfully and output was verified.
APPENDIX - B

TWO MARK AND


16 MARK QUESTIONS WITH ANSWERS

UNIT – I
ALGORITHMIC PROBLEM SOLVING
PART-A
1. Define Algorithm
Algorithm : It is a sequence of instructions designed in such a way that if the instructions are
executed in the specified sequence, the desired results will be obtained. The instructions in an
algorithm should not be repeated infinitely. The algorithm should be written in sequence.

2. What are the properties of algorithm?


•• It is written in simple English.
•• Each step of an algorithm is unique and should be self explanatory.
•• An algorithm must have at least one input.
•• An algorithm must have at least one output.
•• An algorithm has finite number of steps.

3. What are the building block of algorithm?


The three building block of algorithm are :
(1) Sequence
(2) Selection
(3) Iteration

4. What is meant by selection, iteration and sequence control structures?


Sequence:
A sequence is one of the basic logic structures in computer programming. In a sequence
structure, an action, or event, leads to the next ordered action in a predetermined order.

Selection:
A selection (also called a decision) is also one of the basic logic structures in computer
programming. In a selection structure, a question is asked, and depending on the answer, the
program takes one of two courses of action, after which the program moves on to the next
event.
App-B.2 Problem Solving and Python Programming

Selection:
A selection (also called a decision) is also one of the basic logic structures in computer
programming. In a selection structure, a question is asked, and depending on the answer, the
program takes one of two courses of action, after which the program moves on to the next
event.

5. Define Flowchart
It is a pictorial representation of an algorithm. The flowchart uses different shape symbols to
denote the different appropriate instructions and these instructions can be written within the
boxes using clear statements.

6. Write the Characteristics of Pseudo code.


•• Named variables represent data and identifiers denote higher level functions.
•• Composed of a sequence of statements or steps.
•• Statements are often numbered sequentially.
•• Operational (Imperative) statements include assignment, input, and output.
•• Control structures provide iterative and conditional execution. Indentations used for
grouping blocks of statements

7. What is need for flowchart symbol?


The need for flowchart symbols because each symbols of different shapes denotes different
types of instructions. The program logic through flowcharts is made easier through the use of
symbol that has standardized planning.

8. Write some rules for drawing a flowchart.


•• The standard symbols must be used.
•• The arrowhead in the flowchart represents the direction of flow of control in the problem.
•• The usual direction of the flow of procedure is from top to bottom or left to right.
•• The flow lines should not cross each other.
•• Be consistent in using names and variables in the flowchart.
•• Keep the flowchart as simple as possible.

9. What are the advantages of using a flowchart


•• Communication
•• Effective
•• Proper Documentation
•• Efficient Coding
•• Proper Debugging
•• Efficient Program Maintenance
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.3

10. Write any two disadvantages of flowchart.


•• It is not visual
•• We do not get a picture of the design.

11. What is Pseudo code?


“Pseudo” means imitation of false and “code” refers to the instruction written in a programming
language. Pseudo code is programming analysis tool that is used for planning program logic.

12. Write the Characteristics of Pseudocode.


•• Named variables represent data and identifiers denote higher level functions.
•• Composed of a sequence of statements or steps.
•• Statements are often numbered sequentially.
•• Operational (Imperative) statements include assignment, input, and output.
•• Control structures provide iterative and conditional execution.
•• Indentations used for grouping blocks of statemen

13. What are the rules for writing pseudo code?


•• Write one statement per line.
•• Capitalize initial keywords.
•• Indent to show hierarchy.
•• End multiline structure.
•• Keep statements language independent.

14. Write any two advantages of pseudo code.


•• It can be done easily in any word processor.
•• It can be written easily.
•• It can be easily modified as compared to flowchart.

15. Write any two disadvantages of flowchart.


•• It is not visual
•• We do not get a picture of the design.

16. Differentiate Algorithm and Pseudo code


S.No Algorithm Pseudo code
1. It is a well-defined procedure that allows a It is a simple way of writing programming
computer to solve a problem. code in English.
App-B.4 Problem Solving and Python Programming

2. Algorithms can be described in various ways, Pseudo code describes how you would
from pure mathematical formulas to complex implement an algorithm without getting
graphs into syntactical details.

17. What is the difference between algorithm and flowchart


S.No Algorithm Flow Chart
1. Step by Step formation Box by box formation
2. Mostly run to complete or manage a Can be used in general terms to solve any
program implementation. problem related to an individual or a group.
3. More detailed but difficult to understand Less detailed but easy to understand by
everyone.

PART-B
1. Define algorithm. Explain in detail about the building blocks of algorithm.
2. What is flowchart. Explain the Basic design structures in Flowchart
3. What is pseudo code? Explain its guidelines and benefits
4. Explain the design structures in pseudo code.
5. Explain the steps involved in program development cycle
6. Write the algorithm, pseudocode and draw the flowchart for the following:
(a) Find minimum in a list
(b) Insert a card in a list of sorted cards
(c) Guess an integer number in a range
(d) Towers of Hanoi
7. Write the algorithm, pseudocode and draw the flowchart for the following:
(a) To find the sum of square root of any three numbers.
(b) To find the sum of first 100 integers.
(c) To find the sum of all odd numbers till 100.
(d) To find the sum of any five integers.
(e) To find the factorial of number n.
(f) To find the first n numbers in a Fibonacci series.
(g) To find the sum of digits of a number
(h) To find whether a number is prime or not.
(i) To convert temperature from Fahrenheit to Celsius.
(j) To solve the quadratic equation.
(k) To find sum first 100 natural numbers.
(l) To find factorial of a number.
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.5

UNIT - II
DATA, EXPRESSIONS AND STATEMENTS
PART A

1. Define python
Python is an object-oriented, high level language, interpreted, dynamic and multipurpose
programming language.

2. Give the features of python.


•• Easy to Use:
•• Expressive Language
•• Interpreted Language
•• Cross-platform language
•• Free and Open Source
•• Object-Oriented language
•• Extensible

3. What is python interpreter?


The engine that translates and runs Python is called the Python Interpreter: There are two
ways to use it: immediate mode and script mode. The >>> is called the Python prompt. The
interpreter uses the prompt to indicate that it is ready for instructions.

4. What is the difference between intermediate mode and script mode?


In immediate mode, you type Python expressions into the Python Interpreter window, and the
interpreter immediately shows the result.
Alternatively, you can write a program in a file and use the interpreter to execute the contents
of the file. Such a file is called a script. Scripts have the advantage that they can be saved to
disk, printed, and so on.

5. What is meant by value in python?


A value is one of the fundamental things—like a letter or a number—that a program manipulates.

6. List the standard data types in python


Python has five standard data types −
•• Numbers
•• String
•• List
•• Tuple
•• Dictionary
App-B.6 Problem Solving and Python Programming

7. What is meant by python numbers?


Number data types store numeric values. Number objects are created when you assign a value
to them.
Python supports four different numerical types −
•• int (signed integers)
•• long (long integers, they can also be represented in octal and hexadecimal)
•• float (floating point real values)
•• complex (complex numbers)

8. What are python strings?


Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken
using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and
working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator.
str = 'Hello World!'
print str[0] # Prints first character of the string o/p:
H
9. Mention the features of lists in python
Lists are the most versatile of Python's compound data types. A list contains items separated
by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays
in C. One difference between them is that all the items belonging to a list can be of different
data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the
list concatenation operator, and the asterisk (*) is the repetition operator. For example

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] print list[0]
o/p abcd

10. What is tuple ? What is the difference between list and tuple?
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be
updated. Tuples can be thought of as read-only lists.
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.7

Eg:
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )

11. Give the features of python dictionaries


Python's dictionaries are kind of hash table type. They work like associative arrays and consist
of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or
strings. Values, on the other hand, can be any arbitrary Python object.Dictionaries are enclosed
by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For
example −
dict = {}
dict['one'] = "This is one"

12. What is a variable?


One of the most powerful features of a programming language is the ability to manipulate
variables. A variable is a name that refers to a value.
The assignment statement gives a value to a variable: Eg:
>>> n = 17
>>> pi = 3.14159
13. What are the rules for naming a variable?
Variable names can be arbitrarily long. They can contain both letters and digits, but they have to
begin with a letter or an underscore. Although it is legal to use uppercase letters, by convention
we don’t. If you do, remember that case matters. Bruce and bruce are different variables.
The underscore character ( _) can appear in a name.. Eg: my_name

14. What are keywords?


Keywords are the reserved words in Python. We cannot use a keyword as variable name,
function name or any other identifier. They are used to define the syntax and structure of the
Python language In Python, keywords are case sensitive. There are 33 keywords in Python
Eg: False, class, finally, return

15. What are the rules for writing an identifier?


•• Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z)
or digits (0 to 9) or an underscore (_). Names like myClass, var_1 and print_this_to_
screen, all are valid example.
•• An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
•• Keywords cannot be used as identifiers.
•• We cannot use special symbols like !, @, #, $, % etc. in our identifier.
•• Identifier can be of any length.
App-B.8 Problem Solving and Python Programming

16. What are expressions?


An expression is a combination of values, variables, operators, and calls to functions. If you
type an expression at the Python prompt, the interpreter evaluates it and displays the result:
>>> 1 + 1
2
17. What is a statement?
A statement is an instruction that the Python interpreter can execute. When you type a statement
on the command line, Python executes it. Statements don’t produce any result. For example, a
= 1 is an assignment statement. if statement, for statement, while statement etc. are other kinds
of statements

18. What is multiline statement?


In Python, end of a statement is marked by a newline character. But we can make a statement
extend over multiple lines with the line continuation character (\). For example:
a=1+2+3+\
4+5+6+\
7+8+9

19. What is docstring?


Doc string is short for documentation string. It is a string that occurs as the first statement in
a module, function, class, or method definition. It is used to explain in brief, what a function
does.

20. What is a function? Mention the type of function and use.


A Function can be called as a section of a program that is written once and can be executed
whenever required in the program, thus making code reusability. There are two types of
Functions.
(a) Built-in Functions: Functions that are predefined. We have used many predefined
functions in Python.
(b) User- Defined: Functions that are created according to the requirements.

21. Mention the types of arguments in python


(1) python default arguments.
(2) python keyword argument
(3) python arbitrary argument

22. What is meant by module in python?


A module is a file consisting of Python code. A module can define functions, classes and
variables. A module can also include runnable code.
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.9

23. List some built in modules in python


There are many built in modules in Python. Some of them are as follows:math, random ,
threading , collections , os , mailbox , string , time , tkinter etc..

24. What is the use of dir() function?


The dir() built-in function returns a sorted list of strings containing the names defined by a
module. The list contains the names of all the modules, variables and functions that are defined
in a module.

25. What operators does python support?


Python language supports the following types of operators.
•• Arithmetic Operators
•• Comparison (Relational) Operators
•• Assignment Operator
•• Logical Operators
•• Bitwise Operators
•• Membership Operators
•• Identity Operator

26. What is an Arithmetic operator?


Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication etc.
The operators are: +,-,/,%,*,**

27. What is the use of comparison operator?


Comparison operators are used to compare values. It either returns True or False according to
the condition.
>,<,>=,<=,==,!=

28. What are logical operators and Bitwise operators?


Logical operators are the and, or, not operators. Bitwise operators act on operands as if they were
string of binary digits. It operates bit by bit, hence the name. The operators are:&,|,`^,>>,<<

29. What are assignment statements?


Assignment operators are used in Python to assign values to variables.a = 5 is a simple
assignment operator that assigns the value 5 on the right to the variable a on the left.

30. Mention the features of identity operators?


is and is not are the identity operators in Python. They are used to check if two values (or
variables) are located on the same part of the memory. Two variables that are equal does not imply
that they are identical.
App-B.10 Problem Solving and Python Programming

is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same object) x is not True

31. Give the characteristics of membership operator?


in and not in are the membership operators in Python. They are used to test whether a value
or variable is found in a sequence (string, list, tuple, set and dictionary).In a dictionary we can
only test for presence of key, not the value.
Operator Meaning Example
in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

PART - B

1. Explain the data types in python


2. Ilustrate interpreter and interactive mode in python with example.
3. Explain function and module with suitable example
4. Write short notes on types of operators in python with appropriate example
5. Explain briefly constant, variables, expression, keywords and statements available in
python
6. Write the following python programs.
(a) Exchange the value of two variables.
(b) Test whether a given year is leap year or not
(c) To find the sum of n natural numbers
(d) To find whether a given number is Armstrong number or not
(e) To print Fibonacci series
(f) To find factorial of a given number
(g) To convert Celsius to Fahrenheit
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.11

UNIT – III
CONTROL FLOW AND FUNCTIONS
PART A

1. What is Boolean value?


A Boolean value is either true or false. In Python, the two Boolean values are True and False
(the capitalization must be exactly asshown), and the Python type is bool.
>>> type(True)

2. What is Boolean Expression?


•• A Boolean expression is an expression that evaluates to produce a result which is a
Booleanvalue. For example, the operator == tests if two values are equal. It produces
(or yields) aBoolean value:
•• >>> 5 == (3 + 2) # Is five equal 5 to the result of 3 + 2?
•• True

3. What is meant by conditional If?


The if statement in python is used to test a condition. If condition is true, statement of if block
is executed otherwise it is skipped.Syntax of python if statement:
if(condition):
statements

4. What is chained conditional statement?


To check for multiple conditions elif Statement is used.This statement is like executing a if
statement inside a else statement. Syntax:
If statement:
statements elif statement:
statements
else:
statements
5. Write the syntax and usage of for loop
For Loop is used to iterate a variable over a sequence(i.e., list or string) in the order that they
appear.Syntax:
for <variable> in <sequence>:

6. Write the syntax and usage of while loop


While Loop is used to execute number of statements or body till the condition passed in while
is true. Once the condition is false, the control will come out of the loop.
App-B.12 Problem Solving and Python Programming

Syntax:
while <expression>: Body

7. What is python break statement?


Break statement is a jump statement that is used to pass the control to the end of the loop.
Applying break statement makes the loop to terminate and controls goes to next line pointing
after loop body.

8. What is python continue statement?


Continue Statement is a jump statement that is used to skip the present iteration and forces next
iteration of loop to take place. It can be used in while as well as for loop statements.

9. What is python pass statement?


When you do not want any code to execute, pass Statement is used. It is same as the name
refers to. It just makes the control to pass by without executing any code.
Syntax:
pass

10. What is len function and explain how it is used on strings with an example.
The len function, when applied to a string, returns the number or character in a string.
Example:
>>>book=’Problem Solving and Python Programming’
>>>len(book) 38
>>>

11. Explain about string slicing with examples.


A substring of a string is obtained by taking a slice. The operator [n:m] returns the part of the
string from the nth character to the mth character, including the first but excluding the last.
>>>book=’Problem Solving and Python Programming’
>>>print(book[0:7]) Problem
>>>print(book[21:27]) ython

12. What are the two operators that are used in string functions?
The in operator tests for membership.
>>>’V’ in ‘VRB’
True
>>>’S’ in ‘VRB’
>>>False
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.13

The not in operator returns the logical opposite results of in operator.


>>>’x’ not in ‘VRB’ True
13. What is the use of str.upper() and str.lower() functions in string?
The functions str.upper() and str.lower() will return a string with all the letters of original string
converted to upper or lower case letters.
>>>ss=’VRB Publishers’
>>>print(ss.upper()) VRB PUBLISHERS
>>>print(ss.lower()) vrb publishers

14. Explain string comparison with an example.


The comparison operator works on string to check if two strings are equal.
>>>word=’VRB Publishers’
>>>if word==’VRB Publishers’ Print(‘Both are Equal’)
Both are Equal

15. How to split strings and what function is used to perform that operation?
The str.split() method is used to split strings up.
>>>book=’Problem Solving and Python Programming’
>>>print(book.split())
[‘Problem’, ‘Solving’, ‘and’, ‘Python’, ‘Programing’]

PART – B

1. Explain the function arguments in python


2. Explain call by value and call by reference in python 3.Briefly explain about function
prototypes
4. Answer the following questions.
What is String? How do u create a string in Python? (4 marks)
How to perform a user input in Python? Explain with example. (4 marks)
Write a program to check whether entered string is palindrome or not. (8 marks)
5. Answer the following questions.
What is the output produced by this program given below? (8 marks) words = ‘Hello
World’
print words.title()
print words.replace(“World”,’Oswal’) print words.upper()
print words*2
App-B.14 Problem Solving and Python Programming

Assuming num=125, determine the value of each of the following Python expressions.
(8 marks)
(i) num/125
(ii) num%100
(iii) (num==21)&(2<3)
(iv) not((num<45.9)&(6*2<=13))
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.15

UNIT – IV
COMPOUND DATA: LIST, TUPLE, DICTIONARY
PART –A

1. What are tuples in Python?


A tuple is another sequence data type that is similar to the list. A tuple consists ofa number of
values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

2. What is the difference between tuples and lists in Python?


The main differences between lists and tuples are –
Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples
are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read- only
lists.

3. What are Python's dictionaries?


Python's dictionaries are kind of hash table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python
object.

4. Explain how to create a dictionary in python?


Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]).
dict = {}
dict['one'] = "This is one" dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

5. Explain what is range() function and how it is used in lists?


The range function returns an immutable sequence object of integers between the given start
integer to the stop integer.
range(start,stop,[step])
>>>for I in range(1,10,2):
print(i,end=” “) 1 3 5 7 9

6. How lists are updated in Python?


The append() method is used to add elements to a list.
Syntax: list.append(obj) List=[123,’VRB’]
list.append(2017)
Print(“Updated List:”,List)
Output: Updated List: [123,’VRB’,2017]
App-B.16 Problem Solving and Python Programming

7. Write a few methods that are used in Python Lists.


(a) append()- add an element to end of list
(b) insert()- insert an item at the defined index
(c) remove()- removes an item from the list
(d) clear()- removes all items from the list
(e) reverse()- reverse the order of items in the list

8. What are the advantages of Tuple over List?


•• Tuple is used for heterogeneous data types and list is used for homogeneous data types.
•• Since tuple are immutable, iterating through tuple is faster than with list.
•• Tuples that contain immutable elements can be used as key for dictionary.
•• Implementing data that doesn’t change as a tuple remains write-protected.

9. What is indexing and negative indexing in Tuple?


The index operator is used to access an item in a tuple where index starts from 0.
Python also allows negative indexing where the index of -1 refers to the last item, -2 to the
second last item and so on.
>>>my_tuple=(‘p’,’y’,’t’,’h’,’o’,’n’)
>>>print(my_tuple[5]
)n
>>>print(my_tuple[- 6]) p

10. What is the output of print tuple[1:3] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
In the given command, tuple[1:3] is accessing the items in tuple using indexing.
It will print elements starting from 2nd till 3rd. Output will be (786, 2.23).

11. What are the methods that are used in Python Tuple?
Methods that add items or remove items are not available with tuple. Only the following two
methods are available:
(a) count(x)- returns the number of items that is equal to x
(b) index(x)- returns index of first item that is equal to x

12. Is tuple comparison possible? Explain how with example.


The standard comparisons (‘<’,’>’,’<=’,’>=’,’==’) work exactly the same among tuple objects.
The tuple objects are compared element by element.
>>>a=(1,2,3,4,5)
>>>b=(9,8,7,6,5)
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.17

>>>a<
b True

13. What are the built-in functions that are used in Tuple?
•• all()- returns true if all elements of the tuple are true or if tuple is empty
•• any()- returns true if any element of tuple is true
•• len()- returns the length in the tuple
•• max()- returns the largest item in tuple
•• min()- returns the smallest item in tuple
•• sum()- returns the sum of all elements in tuple

14. What is the output of print tuple + tinytuple if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) and
tinytuple = (123, 'john')?
It will print concatenated tuples. Output will be ('abcd', 786, 2.23, 'john', 70.200000000000003,
123, 'john').

15. Explain what is dictionary and how it is created in Python?


Dictionaries are similar to other compound types except that they can use any immutable type
as an index. One way to create a dictionary is to start with the empty dictionary and add
elements. The empty dictionary is denoted {}:
>>> eng2sp = {}
>>> eng2sp[’one’] = ’uno’
>>> eng2sp[’two’] = ’dos’
16. What is meant by key-value pairs in a dictionary?
The elements of a dictionary appear in a comma-separated list. Each entry contains an index
and a value separated by a colon. In a dictionary, the indices are called keys, so the elements
are called key-value pairs.>>> print eng2sp {’one’: ’uno’, ’two’: ’dos’}

17. How does del operation work on dictionaries? Give an example.


The del statement removes a key-value pair from a dictionary. For example, the following
dictionary contains the names of various fruits and the number of each fruit in stock:
>>> inventory = {’apples’: 430, ’bananas’: 312, ’oranges’: 525, ’pears’: 217}
>>> print inventory
{’oranges’: 525, ’apples’: 430, ’pears’: 217, ’bananas’: 312}
If someone buys all of the pears, we can remove the entry from the dictionary:
>>> del inventory[’pears’]
>>> print inventory
{’oranges’: 525, ’apples’: 430, ’bananas’: 312}
App-B.18 Problem Solving and Python Programming

18. What is meant by invocation? Where is it used and how?


A method is similar to a function—it takes arguments and returns a value— but the syntax is
different. For example, the keys method takes a dictionary and returns a list of the keys that
appear, but instead of the function syntax keys(eng2sp), we use the method syntax eng2sp.
keys().
>>> eng2sp.keys() [’one’, ’three’, ’two’]
This form of dot notation specifies the name of the function, keys, and the name of the object
to apply the function to, eng2sp. The parentheses indicate that this method has no parameters.
A method call is called an invocation; in this case, we would say that we are invoking keys on
the object eng2sp.

19. Explain values and items method used in dictionary with example.
The values method is similar; it returns a list of the values in the dictionary:
>>>
eng2sp.values() [’uno’, ’tres’, ’dos’]
The items method returns both, in the form of a list of tuples—one for each key-value pair:
>>> eng2sp.items()
[(’one’,’uno’), (’three’, ’tres’), (’two’, ’dos’)]
The syntax provides useful type information. The square brackets indicate that this is a list. The
parentheses indicate that the elements of the list are tuples.

20. What is the difference between modify and copy operations performed in dictionary?
If you want to modify a dictionary and keep a copy of the original, use the copy method. For
example, opposites is a dictionary that contains pairs of opposites:
>>> opposites = {’up’: ’down’, ’right’: ’wrong’, ’true’: ’false’}
>>> alias = opposites
>>> copy = opposites.copy()
alias and opposites refer to the same object; copy refers to a fresh copy of the same dictionary.
If we modify alias, opposites is also changed:
>>> alias[’right’] = ’left’
>>>
opposites[’right’] ’left’
If we modify copy, opposites is unchanged:
>>> copy[’right’] = ’privilege’
>>> opposites[’right’] ’left
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.19

PART – B

1. Answer the following questions.


Write short note on Functional Programming Approach. (4 marks)
What is the difference between Lists and Tuples? Give an example for their usage. (4
marks)
Explain the purpose of loop structure in a programming language. Describe the syntax
and semantics of any two loop structures provided by Python. (8 marks)

2. Answer the following questions.


Explain the features of a dictionary. (5 marks)
What are the three types of import statement in Python? Explain. (6 marks) Write a short
note on assert function. (5 marks)

3. Answer the following questions.


What is the difference between lists, tuples and dictionaries? Give an example for their
usage. (6 marks)
What type of conditional structures are present in a programming language? How many
of them are supported in Python? Explain each with example. (10 marks)

4. What are the basic list operations that can be performed in Python? Explain each
operation with its syntax and example. (16 marks)

5. What is Dictionary? Explain Python dictionaries in detail discussing its operations and
methods. (16 marks)
App-B.20 Problem Solving and Python Programming

UNIT – V
FILES, MODULES AND PACKAGES
PAR T – A

1. What is module and package in Python?


In Python, module is the way to structure program. Each Python program file is a module,
which imports other modules like objects and attributes.

2. Explain how can you access a module written in Python from C?


We can access a module written in Python from C by following method,Module = =PyImport_
ImportModule(“<modulename>”);

3. Mention five benefits of using Python?


•• Python comprises of a huge standard library for most Internet platforms like Email,
HTML, etc.
•• Python does not require explicit memory management as the interpreter itself allocates
the memory to new variables and free them automatically
•• Provide easy readability due to use of square brackets
•• Easy-to-learn for beginners
•• Having the built-in data types saves programming time and effort from declaring
variables

4. How to open a new file in Python?


Opening a file creates a file object. In this example, the variable f refers to the new file
object. >>> f = open("test.dat","w")

>>> print f<open file ‘test.dat’, mode ‘w’ at fe820> The open function takes two arguments.
The first is the name of the file, and the second is the mode. Mode "w" means that we are opening
the file for writing.

5. Explain how the write method works on a file.


To put data in the file we invoke the write method on the file object:
>>> f.write("Now is the time")

>>> f.write("to close the file")

Closing the file tells the system that we are done writing and makes the file available for
reading:
>>> f.close()
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.21

6. Which method is used to read the contents of a file which is already created?
The read method reads data from the file. With no arguments, it reads the entire contents of the
file:
>>> text = f.read()
>>> print text
Now is the timeto close the file

7. What is a text file? Give an example for a text file.


A text file is a file that contains printable characters and whitespace, organized into lines
separated by newline characters.
To demonstrate, we’ll create a text file with three lines of text separated by newlines:
>>> f = open("test.dat","w")
>>> f.write("line one\nline two\nline three\n")
>>> f.close()

8. What is the difference between break and continue statement?


The break statement is new. Executing it breaks out of the loop; the flow of execution moves to
the first statement after the loop.
The continue statement ends the current iteration of the loop, but continues looping. The flow
of execution moves to the top of the loop, checks the condition, and proceeds accordingly.

9. What is meant by directory? How and where is it useful?


When we want to open a file somewhere else, you have to specify the path to the file, which is
the name of the directory (or folder) where the file is located:
>>> f = open("/usr/share/dict/words","r")
>>> print f.readline() Aarhus
This example opens a file named words that resides in a directory named dict, which resides
in share, which resides in usr, which resides in the top-level directory of the system, called .

10. Explain pickling and how import pickle works.


Pickling is so called because it “preserves” data structures. The pickle module contains the
necessary commands. To use it, import pickle and then open the file in the usual way:
>>> import pickle
>>> f = open("test.pck","w")

11. What is an exception? Explain with few examples.


Whenever a runtime error occurs, it creates an exception. Usually, the program stops and
Python prints an error message.
App-B.22 Problem Solving and Python Programming

For example,
dividing by zero creates an exception:
>>> print 55/0
ZeroDivisionError: integer division or modulo So does accessing a nonexistent list item:
>>> a = []
>>> print a[5]
IndexError: list index out of range Or accessing a key that isn’t in the dictionary:
>>> b = {}
>>> print b[’what’] KeyError: what

12. List some few common Exception types and explain when they occur.
ArithmeticError- Base class for all errors that occur for numeric calculations.
OverflowError- Raised when a calculation exceeds maximum limit for a numeric type.
ZeroDivisionError- Raised when division or modulo by zero takes place. ImportError- Raised
when an import statement fails.
IndexError- Raised when an index is not found in a sequence.
RuntimeError- Raised when a generated error does not fall into any category.

13. Write a simple program which illustrates Handling Exceptions.


while True: try:
x=int(input(“Please enter a number:”)) break
except ValueError:
print(“Oops! That was no valid number. Try again…”)

14. What are packages in Python?


A package is a collection of Python modules. Packages allow us to structure a collection of
modules. Having a directory of modules allows us to have modules contained within other
modules. This allows us to use qualified module names, clarifying the organization of our
software.

15. Explain what is meant by namespaces and scoping.


Variables are names or identifiers that map to objects. A namespace is a dictionary of variable
names/keys and their corresponding object values. A python statement can access variables in
a local namespace and global namespace. If the local and global variables have the same name,
the local variable shadows the global variable. Each function has its own local namespace.
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.23

PART – B
1) Answer the following questions.
(a) Write a small code to illustrate try and except statements in Python. (4 marks)
(b) What are packages? Give an example of package creation in Python. (4 marks)
(c) Compare and contrast Extending and Embedding Python. (4 marks)
(d) Write an algorithm to check whether a student is pass or fail, the total marks of stu-
dent being the input. (4 marks)
2) Answer the following questions.
(a) Write a program to enter a number in Python and print its octal and hexadecimal
equivalent. (6 marks)
(b) Demonstrate the use of Exception Handling in Python.(10 marks)
3) Answer the following questions.
(a) What are modules in Python? Explain. (4 marks)
(b) Explain in details about namespaces and scoping. (8 marks)
(c) Explain about the import statement in modules. (4 marks)
4) Answer the following questions.
(a) Explain about the different types of Exceptions in Python. (6 marks)
(b) Describe about Handling Exceptions in detail with examples. (10 marks)
5) Explain in detail about Python Files, its types, functions and operations that can be
performed on files with examples. (16 marks)
APPENDIX - C

PREVIOUS YEAR
UNIVERSITY QUESTION PAPER

B.E./B.Tech. DEGREE EXAMINATION, 2017


First Semester Civil Engineering
GE8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING
(Common to All Branches) (Regulations 2017)
Time : Three Hours Maximum : 100 Marks
Answer ALL questions
PART – A(10×2=20 Marks)
1. What is an algorithm ?
2. Write a pseudo-code to accept two numbers, add the numbers and print the result.
3. Outline the modes Python interpreter works.
4. State the difference between (I) and (II) operators in Python.
5. Write a Python program to accept two numbers, find the greatest and print the result.
6. What is recursion ?
7. What is a list in Python ? Give example.
8. Write the syntax for concatenating two lists in Python.
9. What is an exception ? Give example.
10. Write the syntax for opening a file in Python for reading only.

PART – B(5×16=80 Marks)


11. a) i) Explain with an example the boilding blocks of an algorithm. (8)
ii) Draw a flow chart to print the first ‘n’ prime numbers. (8)
(OR)

b) Explain with relevant diagrams and algorithm the Towers of Hanoi problem. (16)
12. a) i) Explain with an example the structure of a Python program. (8)
App-C.2 Problem Solving and Python Programming

ii) Outline with an example the assignment operators supported in Python. (8)
(OR)
b) Explain the various data types in Python. (16)
13. a) i) Write a Python program using while loop to print the first n numbers divisible
by 5. (8)
ii) Write a Python program to compute the factorial of a given number. (8)
(OR)
b) Write Python program to perform binary search. (16)
14. a) Write code snippets in Python to perform the following :
i) Accessing elements of a tuple. (5)
ii) Modifying elements of a tuple. (5)
iii) Deleting elements of a tuple. (6)
(OR)
b) Write the Python program to sort an integer list using selection sort. (16)
15. a) Describe in detail how exceptions are handled in Python. Give relevant examples. (16)
(OR)
b) Write a Python program to copy the contents of one file to another. (16)
———————

Вам также может понравиться