0% found this document useful (0 votes)
39 views250 pages

Python All Units New2

Uploaded by

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

Python All Units New2

Uploaded by

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

Problem Solving and Python Programming 2020

CHAPTER 1

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, and guess an integer number in a range, Towers of
Hanoi.

1
Problem Solving and Python Programming 2020

2
Problem Solving and Python Programming 2020

ALGORITHMIC PROBLEM SOLVING


1.1 ALGORITHM

Algorithm is defined as the effective step-by-step procedure to solve the problem in a


finite number of steps.

Input Algorithm Output

Fig 1.1: Algorithm and Input/Output Relationship


Algorithm is an ordered set of rules to solve a problem. It is a representation of a solution
to a problem. It is a well-defined computational procedure consisting of a set of instructions that
takes some value or set of values, as input, and produces some value or set of values, as output.
Program=Algorithm +Data Structures

1.1.1 Characteristics of an algorithm

i) Each and every instruction should be precise and unambiguous.


ii) Algorithm should have finite number of steps.
iii) Algorithm should be written in sequence (step-by step).
iv) Algorithm should have finite number of inputs.
v) Ensure that the algorithm will terminate.
vi) Results should be obtained only after the algorithm terminate.
1.1.2 Qualities of a good algorithm

i) Time: A good algorithm should take less time to execute the program.
ii) Memory: A good algorithm should take less memory space to execute the program.
iii) Accuracy: A good algorithm should provide more accurate results.
iv) Sequence: A good algorithm should be written in sequence (step-by-step).
v) Understandability: A good algorithm should be easily understandable.
vi) Solvability: A good algorithm should solve the problem.
1.1.3 Two important factors of an algorithm

Time complexity: It is the amount of time required to complete a task.


Space complexity: It is the amount of memory space required to complete a task.

3
Problem Solving and Python Programming 2020

1.1.4 Key features of an algorithm

Sequence: Each instruction is executed in sequence (step-by-step).


Decision: The result is based on some condition.
Repeat: Process is repeated until condition becomes false.
1.1.5 Steps to develop an algorithm

i) An algorithm should be enclosed by two statements START and STOP.


ii) To read data from user INPUT or READ statement is used.
iii) To display the output PRINT statement is used.
iv) The arithmetic operators used are
+ - Addition operator
- - Subtraction operator
* - Multiplication operator
/ - Division operator
= - Assignment operator
v) Commonly used relational operators are
> -- Greater than
< -- Less than
>= -- Greater than or equal to
<= -- Less than or equal to
== -- Equal to
vi) The commonly used logical operators are
AND, OR, NOT
Example 1: Write an algorithm to find the sum of two numbers.

1. Start
2. Print “Enter two numbers:”
3. Read A, B
4. C=A+B
5. Print C
6. Stop

4
Problem Solving and Python Programming 2020

Example 2: Write an algorithm to swap two numbers.

1. Start
2. Print “Enter two numbers:”
3. Input a, b
4. c = a
5. a = b
6. b = c
7. Print a, b
8. Stop
Example 3: Construct an algorithm to check whether the given number is odd or even.

1. Start
2. Print “Enter two numbers:”
3. Read n
4. r = n%2
5. If r = 0 then
6. Print “Number is even”
7. If r! =0 then
8. Print “Number is odd”
9. Stop
Example 4: Write an algorithm to find the area of the circle.

1. Start
2. Print “Enter radius:”
3. Input r
4. a = 3.14*r*r
5. Print a
6. Stop
1.2 BUILDING BLOCKS OF AN ALGORITHM

Algorithm is defined as the effective step-by-step procedure to solve the problem in a


finite number of steps. Algorithms can be designed using the following components. They are
5
Problem Solving and Python Programming 2020

i) Instructions/Statements
ii) State
iii) Control Flow
iv) Functions
1.2.1 Instructions/Statements

Instructions/Statements are the steps which solves a particular problem. Most algorithms
have the basic parts of statements.
→ Description of the problem.
→ Setup
→ Parameters
→ Execution
→ Conclusion
Example: To find the sum of two numbers.
Description of the problem:
To find the sum of two numbers.
Setup:
Two numbers required for addition and one variable for storing the result.
Parameters:
1. Read first number.
2. Read the second number.
Execution:
Calculate the sum of two numbers (a,b)
result = a + b
Conclusion:
The desired output is the sum of two numbers which is stored in the variable ‘result’.

1.2.2 State

State is defined as the condition of algorithm at a moment in a time. Algorithm can be in


any of the following states.
1. START state
2. INPUT state
6
Problem Solving and Python Programming 2020

3. PROCESS state
4. OUTPUT state
5. STOP state

START INPUT PROCESS

STOP OUTPUT

Fig 1.2: States of an algorithm


1. START state:
It represents the starting of the program.
2. INPUT state:
It represents the process of reading the input from the user.
3. PROCESS state:
It represents the process done in the program. E.g. Addition, Subtraction etc..
4. OUTPUT state:
It represents the output displayed on the screen.
5. STOP state:
It represents the ending of the program.
Example: Algorithm to find the sum of two numbers.

1. Start (START state)


2. Read A, B (INPUT state)
3. C=A+B (PROCESS state)
4. Print C (OUTPUT state)
5. Stop (STOP state)
1.2.3 Control flow

It represents the order of statement execution and direction of flow of programs.


There are three types of control flow.

7
Problem Solving and Python Programming 2020

i) Sequential control flow.


ii) Selection control flow.
iii) Repetition control flow.
i) Sequential control flow
The steps of an algorithm are carried out in a sequential manner.

Statement 1

Statement2

Statement3

Example: Temperature conversion


1. Start
2. Read temperature in fahrenheit f.
3. c = (5/9)*(f-32)

4. Print c
5. Stop
Flowchart:

Start

Read F

c=(5/9)*(f-32)

Print c

STOP

8
Problem Solving and Python Programming 2020

ii) Selection control flow

Only one of the alternative steps is executed based on the condition.

Yes No
Condition

Statement 1 Statement 2

Example: Algorithm to find the biggest among two numbers.

1. Start
2. Read a, b
3. If a>b then Print “a is big”
4. Else Print “b is big”
5. Stop

Yes No
If
A>B

A is BIG B is BIG

iii) Repetition control flow

One or more steps are performed repeatedly. This logic is used for producing loops in the
program. The looping process can either be one time or multiple times based on the condition.
9
Problem Solving and Python Programming 2020

No
Condition Statement 2

Yes

Statement 1

Example: Algorithm to print numbers from 1 to 10.

1. Start
2. Initialize n=0
3. Increment n=n+1
4. Print n
5. If n<=10 then goto step 3
6. Else goto step 7
7. Stop
Flowchart:
Start

n=0

n= n+1

Print n

Yes
If
n<=10

No
Stop

10
Problem Solving and Python Programming 2020

1.2.4 Functions

→A function is a block of organized, reusable code which is used to perform a task or


action.
→It provides better modularity.
→They are also called as methods, routines, procedures etc.
→“Add” is a function and it performs addition operation.
Example: Algorithm to find the biggest among N numbers.

1. Start
2. Read l1, l2, l3…ln into array.
3. Initialize max=l1
4. Read next number l1, do the following
i. If max< l1 then
I) max = l1
ii. Repeat step” i” until n
5. Print max
6. Stop
1.2.5 Advantages of algorithm
i) Easy to understand.
ii) Easy to debug.
iii) It is easy for a programmer to convert algorithm into actual program.
1.2.6 Disadvantages of algorithm
i) It is time consuming. (An algorithm is developed first, which is then converted into
flow chart and then program).
ii) It is difficult to show branching and looping.
1.3 NOTATION
1.3.1 Pseudo code
Pseudo code is made up of two words: Pseudo and code. Pseudo means ‘imitation’ and
‘code’ refers to instructions written in programming language. Pseudo code is not a real
programming language, but it looks like a programming language. Pseudo code is also called as
“Program Design Language [PDL]”. It is an outline of a program, written in a form that can be
11
Problem Solving and Python Programming 2020

easily converted into real programming statements. Pseudo code instructions are written in
normal English.
Rules for writing pseudo code:

i) Write one statement per line.


ii) Capitalize the keywords.
iii) End Multiline structure.
iv) Keep Statements language independent.
v) Intend to show hierarchy.
Keywords used in pseudo code:
START: BEGIN
INPUT: READ, OBTAIN, GET, INPUT, DEFINE
OUTPUT: OUTPUT, PRINT, DISPLAY, SHOW
COMPUTE:CALCULATE, COMPUTE, ADD, SUBTRACT, INITIALISE,
DETERMINE
INITIALIZE: SET, INITIALIZE
ADD ONE: INCREMENT
STOP: END
Pseudo code guidelines:
i) Pseudo code statements should be written in simple English.
ii) Each statement should be written in separate line.
iii) The keywords should be capitalized.
iv) Pseudo code should be programming language independent.
v) The steps must be understandable.
vi) Each set of instructions are written from top to bottom.
Advantages (Benefits):

→ It can be read and understood easily.


→ It can be done easily on a word processor.
→ It can be modified easily.
→ It occupies less space.
→ It will not run over many pages.
12
Problem Solving and Python Programming 2020

→ Converting a pseudo code to a program is simple.


Disadvantages (Limitations):

→ It is not visual.
→ We do not get a picture of the design.
→ There is no standardized style or format.
→ For a beginner, it is more difficult to follow the logic or write pseudo code.
Example 1: Write Pseudo code to calculate sum and average for n numbers.

BEGIN
INITIALIZE sum=0, i=1
READ n
FOR i < = n, then
COMPUTE sum = sum +i
CALCULATE i=i+1
END FOR
COMPUTE avg = sum/n
PRINT sum, avg
END
Example 2: Write Pseudo code to add two numbers.

BEGIN
SET C=0
READ A, B
ADD C=A+B
PRINT C
END
Example 3: Write Pseudo code to calculate area of circle.

BEGIN
READ radius r
INITIALIZE pi=3.14
CALCULATE Area=pi * r *r
13
Problem Solving and Python Programming 2020

PRINT Area
END
Example 4: Write Pseudo code to read number n and print the integers counting up to n.

BEGIN
READ n
INITIALIZE i to 1
FOR i <= n, then
DISPLAY i
INCREMENT i
END FOR
END
Example 5: Write Pseudo code to find the greatest among two numbers.

BEGIN
Read A, B
IF A >B
PRINT “A is greatest”
ELSE
PRINT “B is greatest”
ENDIF
END
1.3.2 Flowchart

Flowchart is a diagrammatic representation of an algorithm. A flowchart is a picture of


the separate steps of a process in sequential order. Flowchart is made up of boxes, diamonds and
other shapes connected by arrows where each shape represents a step in the process. The arrows
show the order of the flow of execution. Flowcharts are used in designing or documenting a
process or program. The logic of the program is communicated in a much better way by using a
flowchart.

14
Problem Solving and Python Programming 2020

Flowchart symbols:

Sl.No Name of the symbol Symbol Description

1 Represent the start and stop of the


Start/Stop
program

2 Denoted either an input or output


Input/Output operation

3 Process Denotes the process to be carried out

Represent decision making and


4 Decision branching

5 Flow lines Represents the sequence of steps and


direction of flow

Connects remote parts of the flowchart


6 Connector on the same page

Stored on magnetic tape


7 Magnetic tape

Magnetic disk I/O from magnetic disk


8

Wait
9 Delay

10 OR Logical OR

Logical AND
11 AND

15
Problem Solving and Python Programming 2020

A Document
12 Document

Sort in some order


13 Sort

Guidelines for drawing flowchart:


i) All necessary requirements should be listed out in logical order.
ii) There should be START and STOP in the flowchart.
iii) The flowchart should be clear, neat and easy to follow.
iv) The direction of flow is from left to right or top to bottom.
v) Only one flow line should emerge from a process symbol.

vi) Only one flow line should enter a decision symbol but 2 or 3 flow line can leave the decision
symbol.

vii) Only one flow line is used with terminal symbol.

START STOP

viii) If the flowchart becomes complex, connector symbols are used to reduce the number of
flow lines.
ix) The text within the symbols should be brief.
x) The validity of flowchart should be tested by passing simple test data.
16
Problem Solving and Python Programming 2020

Basic design structure of flowchart:

Start

Read

Process

Output

Stop

Advantages:
i) Better communication
It is easy for the programmer to explain the logic of program.
ii) Effective analysis
It is easy to analyze the problem effectively.
iii) Proper documentation
With the help of flowchart good documentation is done for various purposes.
iv) Efficient coding
Flowchart acts as a guide during the system analysis and program development phase.
v) Efficient debugging
It helps in debugging process.
vi) Efficient program maintenance
The maintenance of a program becomes easy with the help of the flowchart.
Disadvantages (Limitations):
i) Complex logic
Sometimes the logic of the program is quite complicated. In such a case flowcharts
become complex.

17
Problem Solving and Python Programming 2020

ii) Alterations and modifications


If alterations are required, the flowchart needs to be redrawn completely.
iii) Reproduction
Reproduction of the flowchart becomes a problem because it cannot be typed.
iv) Cost
High cost for large applications.
Example1: Draw a flowchart to add two numbers.

Start

Read num1, num2, sum

sum = num1+num2

Print sum

Stop

Example2: Draw a flowchart to find the product of two numbers.

Start

Read num1, num2, product

product =num1*num2

Print product

Stop

18
Problem Solving and Python Programming 2020

1.3.3 Programming languages

Programming languages are used to communicate instructions to the computer.


Programming languages are written based on syntactic and semantic rules.
Programming languages can be divided into nine major categories.
i) Interpreted programming language
ii) Functional programming language
iii) Compiled programming language
iv) Procedural programming language
v) Scripting programming language
vi) Markup programming language
vii) Logic-based programming language
viii) Concurrent programming language
ix) Object-Oriented programming language
i) Interpreted programming language

An interpreted programming language is a programming language that executes


instructions directly, without compiling a program into machine-language instructions.
Example: BASIC (Beginners All Purpose Symbolic Instruction Code), LISP (List Processing
Language), Python.
ii) Functional programming language

Functional Programming languages define every computation as a mathematical


evaluation. They are based on mathematical functions. They focus on application of functions.
Example: Clean, curry, F#, Haskell and Q
iii) Compiled programming language
Compiled Programming language is a programming language which uses compilers to
convert the source code into machine code.
Example: Ada, algol, C,C++,C#, COBOL, Java, Fortran, VB
iv) Procedural programming language
A procedural language is a type of computer programming language that specifies a
series of well-structured steps and procedures within its programming context to compose a

19
Problem Solving and Python Programming 2020

program. These languages specify the steps that the program should take to reach to an intended
state. Procedure is a group of statements. It makes the program structured and helps to reuse the
code.
Example: CLIST, Hypertalk, MATLAB, PL/I
v) Scripting programming language
Scripting languages are Programming languages that control applications.
Example: AppleScript, AWK, MAYA, PHP, VBSCRIPT.
vi) Markup programming language
Markup language is an artificial language that define how the text to be displayed.
Example: CURL, SGML, HTML, XML, XHTML.
vii) Logic-based programming language
Logic-based programming language is a type of programming language that is based on
logic.
Example: ALF, Fril, Janus, Leda, Prolog.
viii) Concurrent programming language
It is a computer programming language that executes the operations concurrently.
Example: ABCL, Afnix, E, Joule, Limbo.

ix) Object-Oriented programming language


It is a Programming languages based on concepts of objects. Objects contain data and
functions.
Example: Agora, Beta, Lava, Moto, Scala, Slate.
Machine language:
In machine language, instructions are in the form of 0’s and 1’s. Instructions in machine
language consist of two parts.

OPCODE OPERAND

→ OPCODE tells the computer what functions are to be performed.


→ OPERAND tells the computer where to store the data.
Assembly language:
In assembly language, mnemonic code is assigned to each machine language instruction
which is easy to remember and write. Instruction in assembly language consists of 4 parts.
20
Problem Solving and Python Programming 2020

LABEL OPCODE OPERAND COMMENT


4GL language:
4GL (Fourth generation languages) are simple which is used to access databases.

1.4 ALGORITHMIC PROBLEM SOLVING

Algorithms are procedural solutions to problems. Algorithmic problem solving is defined


as the formulation and solution of problems where solution involves the principles and
techniques to construct the correct algorithms. It means that solving problems that require
formulation of an algorithm for their solution.
1.4.1 Steps in designing and analyzing an algorithm
The steps are
i) Understanding the problem
ii) Ascertaining the capabilities of a computational device
iii) Choosing between exact and approximate problem solving
iv) Deciding on appropriate data structures.
v) Algorithm design techniques
vi) Methods of specifying an algorithm.
vii) Proving an algorithm’s correctness.
viii) Analyzing an algorithm.
ix) Coding an algorithm.
i) Understanding the problem
→Before designing an algorithm, you need to understand the problem completely.
→Read the problem description carefully.
→ Check if it is similar to some standard problems and if a known algorithm exists.
→Ask Questions if you have any doubts and do a few small examples by hand.
→Think about special cases.
→Ask Questions again if needed.

21
Problem Solving and Python Programming 2020

Understand the problem

Decide on: computational


means,

Algorithm design techniques

Design an algorithm

Prove correctness

Analyze the algorithm

Code the algorithm

Fig 1.3: Steps in designing and analyzing an algorithm

ii) Ascertaining the capabilities of a computational Device

The second step is to ascertain the capabilities of a machine.


Sequential algorithms:
→ The essence of von-Neumann machines architecture is captured by RAM; here the
instructions are executed one after another, one operation at a time.
→Algorithms designed to be executed on such machines are called sequential algorithms.

22
Problem Solving and Python Programming 2020

Parallel algorithms:
→ An algorithm which has the capability of executing the operations concurrently is
called parallel algorithms.
→ RAM model doesn’t support this.
iii) Choosing between exact and approximate problem solving

→The next decision is to choose between solving the problem exactly or solving it
approximately.
→Based on this, the algorithms are classified as exact and approximation algorithms.
Exact algorithms:

→ The algorithms that can solve the problem exactly are called exact algorithms.

Approximate algorithms:

→The algorithms that can solve the problem not exactly are called approximate
algorithms.
→There are three issues to choose an approximation algorithm.
→First, there are certain problems like extracting square roots, solving non-linear
equations which cannot be solved exactly.
→Secondly, if the problem is complicated it slows the operations. E.g. Traveling
salesman problem.
→Third, this algorithm can be a part of a more sophisticated algorithm that solves a
problem exactly.
iv) Deciding on appropriate data structures

→Data structures play a vital role in designing and analyzing the algorithms.
→Some of the algorithm design techniques also depend on the structuring data specifying
a problem’s instance.
Algorithm + Data structure = Programs
v) 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.

23
Problem Solving and Python Programming 2020

→Learning these techniques is important for two reasons.


i) First, they provide guidance for designing for new problems.
ii) Second, algorithms are the cornerstones of computer science.
vi) Methods of specifying an algorithm
Once you have designed an algorithm, you need to specify it in some fashion.
There are two options for specifying algorithms.
→ Pseudo code
→ Flowchart
Pseudo code is a mixture of a natural language and programming language. It is more
precise.
Flowchart is a method of expressing an algorithm by a collection of connected geometric
shapes containing descriptions of the algorithm’s steps.
vii) Proving an algorithm’s correctness

→Once an algorithm has been specified, you have to prove its correctness.
→You have 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.
viii) Analyzing an algorithm

→ Our algorithm should possess several qualities.


→ Analysis of algorithms and performance analysis refers to the task of determining how
much computing time and storage an algorithm requires.
→After correctness, the most important quality of an algorithm is Efficiency.
→There are two kinds of algorithm Efficiency.
i) Time efficiency: It indicates how fast the algorithm runs.
ii) Space efficiency: Indicates how much extra memory the algorithm needs.
ix) Coding an algorithm
→ Algorithms are implemented as computer programs.
→ Verification and validation is done for error correction.

24
Problem Solving and Python Programming 2020

1.5 SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS

Iteration and Recursion are the simple strategies for developing algorithms.

1.5.1 Iteration

Iteration is the process of repeating the same set of statements again and again until the
condition becomes false. Iteration is done in two ways.
i) In iteration loop, the condition is checked at the beginning of the loop. If the condition
is true, then the loop will be executed. If the condition is false, the loop will not be executed.

No
If
condition

Yes

Body of the loop

ii) Condition is checked at the bottom of the loop. If the condition is true, loop will be
executed. Otherwise the loop will not be executed.

Body of the loop

Yes
If
condition

No

25
Problem Solving and Python Programming 2020

Example: Write an algorithm, pseudo code and draw the flowchart to print the numbers from 1
to 10.
Algorithm:
1. Start
2. Initialize n=0
3. Increment n by 1
4. Print n
5. Check condition n<10
i. If yes goto step 3
ii. Otherwise goto step 6
6. Stop
Flowchart:

Start

n=0

n= n+1

Print n

Yes
If
n<10
No

Stop
Pseudo code:
BEGIN
OBTAIN n
INITIALIZE n=0

26
Problem Solving and Python Programming 2020

INCREMENT n=n+1
DISPLAY n
IF n<10 REPEAT the loop
ENDIF
END
1.5.2 Recursion

Recursion is a programming technique that has a recursive function that calls itself again
and again until the condition is reached.
Syntax:
function():
function():

In the above syntax, function() is a function which call itself until the condition is reached.
1.5.3 Difference between recursion and iteration

Sl.No Recursion Iteration


1 Function calls itself until the Repetition of loop until condition
base condition is reached. fails.
2 It keeps code short and It keeps the code longer.
simple.
3 It is slower. It is faster.
4 It takes more memory. It takes less memory.
5 Tracing is difficult if any Tracing is easier if any problem
problem occurs. occurs.

Example: Calculating factorial of a number using recursion.


Algorithm:
1. Start
2. Read n
3. Call the function fact(n)
4. Print value of the factorial

27
Problem Solving and Python Programming 2020

5. Stop
fact(n) function:
1. Start function
2. If n=0, return 1
3. If n>0 return function fact(n)
4. Return
Flowchart :

The recursive function used to calculate factorial of a number is


fact(n) = 1 if n=0
fact(n) =
n *fact(n-1) if n>0.

fact(n)
Start

Read n

if

n=0
fact = fact(n)

Print fact Return Return


n*fact(n-1) 1

Stop

28
Problem Solving and Python Programming 2020

1.6 ILLUSTRATIVE PROBLEMS

1.6.1 Finding minimum in a list

Problem description:

The problem is to find the minimum element in the given list of elements. Finding
minimum in a list of elements can be achieved in different ways. One way is to sort the list of
elements in ascending order and get the first element as minimum. Another method is to compare
each element with other. As an initial step, first element of the list is considered as minimum
element. And in each iteration, each element in the list is compared with the minimum. If the
element in the list is less than the minimum then swap both elements else compare with the next
element in the list. These steps are continued until the end of the list and finally print the
minimum.
Algorithm:

1. Start.
2. Read the list of elements.
3. Set first element in the list as minimum.
4. Move to the next element in the list.
5. If current element<minimum then
Set minimum =current element.

6. Repeat Step 4 and Step 5 until the end of the list is reached.
7. Print the minimum value in the list
8. Stop
Pseudo code:

BEGIN
READ the list of elements.
INITIALIZE min with the first element of the list
FOR each element in the list of elements
IF element is less than min
COPY element to min

29
Problem Solving and Python Programming 2020

ENDIF
ENDFOR
PRINT min as the minimum value
END
Flowchart:
Start

Read list of n elements, i

min = element[0]
i=1

No
if i<n

If
element[
i] < min
No
e

min=element[i]

i= i+1

Print min
elements, i

Stop

1.6.2 To insert a card in a list of sorted card

Playing cards are one of the techniques of sorting and the steps are shown as
follows: Start with an empty left hand and cards face down on the table. Then remove one card

30
Problem Solving and Python Programming 2020

at a time from the table and Insert it into the correct position in the left hand. To find a correct
position for a card, we compare it with each of the cards already in the hand from left to right.
Once the position is found, the cards from that position are moved to the next higher indexed
position and in that order. New card is inserted at the current position.
Algorithm:
1. Start
2. Read the list of sorted cards.
3. Read the new card.
4. Insert a new card to the end of the list.
5. For i=1 to len(a)
6. current_card=a[i]
7. pos=i
8. While pos>0 and a[pos-1]>current_card
9. a[pos]=a[pos-1]
10. pos=pos-1
11. a[pos]=currentcard
12. Print sorted list of cards.
13. Stop

Pseudo code:

BEGIN
READ the list of sorted cards.
READ the new card.
ADD new card to the end of the sorted list.
FOR i=1 to len(a)
current_card=a[i]
pos=i
WHILE pos>0 and a[pos-1]>current_card
a[pos]=a[pos-1]
a[pos]=current_card
ENDWHILE
31
Problem Solving and Python Programming 2020

PRINT sorted card list.


END
Flowchart:
Start

position = 1

No
position
<
length

Yes

location = Position

No
location>0 &&
position=position+1 cards[location] <

cards[location-1]

yes

Swap card[location]<cards[location-1]

location=location-1

Stop

32
Problem Solving and Python Programming 2020

1.6.3 Guess an integer number in a range

Guessing game – guessing a number within a range of numbers.

Algorithm:
1. Start
2. Read n.
3. Read a guess number.
4. If guess > n
5. Print “Your guess is too high”
6. If guess < n
7. Print “ Your guess is too low”
8. Else
9. If guess = n
10. Print “Good job” else print “no”
11. Stop
Pseudo code:

BEGIN
READ n
OBTAIN guess
IF guess > n
DISPLAY “Your guess is too high”
IF guess < n
DISPLAY “Your guess is too low”
ELSE
IF guess=n
DISPLAY “Good Job” ELSE DISPLAY “No’
ENDIF
ENDIF
ENDIF
END

33
Problem Solving and Python Programming 2020

Flowchart:

start

Read n

Read guess

if No
guess >n

Yes
if No

Print “Too high” guess< n

Yes No
if
Print “Too Low”
guess>=n

Yes

Print “Good No
Job”

Stop

34
Problem Solving and Python Programming 2020

1.6.4 Tower’s of Hanoi

A Tower’s of Hanoi is a children’s playing game, played with three poles and a number
of different sized disks which is stacked on the poles. The disks are stacked on the left most pole
in ascending order initially. ie) The largest on the bottom and the smallest on the top.
Rules to be followed:
i) Only one disk can be moved among the towers at any given time.
ii) Only the “top” disk can be removed.
iii) No large disk can sit over a small disk.
The objective is to transfer the disks from the left most pole to the right most pole by
using the centre pole as the temporary pole.
The steps are
i) Move the top n-1 disks from the left pole to the centre pole, n is the number of disks.
ii) Move the nth largest disk to the right pole.
iii) Move the n-1 disks on the centre pole to the right pole.
The total number of moves will be 2n – 1, where n is the number of disks.
Algorithm:

1. Start
2. Read disk, source, dest, aux
3. Call the function Hanoi(disk, source, dest, aux)
4. Stop
Algorithm for function Hanoi(disk, source, dest, aux):

1. Start
2. If disk=1
Move disk from source to dest
3. Else
3.1 Hanoi(disk-1, source, aux, dest)
3.2 Move disk from source to dest
3.3 Hanoi(disk-1, aux, dest, source)
4. Return

35
Problem Solving and Python Programming 2020

A B C

1 2

A B C A B C

4
3

A B C A B C

5 6

A B C A B C

A B C

Fig 1.4: Tower’s of Hanoi with 3 disks

36
Problem Solving and Python Programming 2020

Flowchart:

Hanoi()
Start

Read disk
If

n=1
Define function

Hanoi()
Move disk from souce to
dest

Call the function


Hanoi() Call function Hanoi()

Stop
Move disk from source to
dest

Call function Hanoi()

Return

Pseudo code:

BEGIN
READ disk, source, dest, aux
FUNCTION Hanoi (disk, source, dest, aux)
END

37
Problem Solving and Python Programming 2020

Pseudo code for function Hanoi (disk, source, dest, aux)


BEGIN
IF disk=1 THEN
Move disk from source to dest
ELSE
Hanoi (disk-1, source, aux, dest)
Move disk from source to dest
Hanoi (disk-1, aux, dest, source)
ENDIF
END

38
Problem Solving and Python Programming 2020

PART A (2 Marks with Answers)

1. Define Algorithm. (JANUARY 2018)


Algorithm is defined as the effective step-by-step procedure to solve the problem in a
finite number of steps. It is an ordered set of rules to solve a problem. An algorithm is a
representation of a solution to a problem.
2. What are the basic building blocks of an algorithm?
Algorithm is defined as the effective step-by-step procedure to solve the problem in a finite
number of steps. The basic building blocks of an algorithm are
i) Instructions/Statements
ii) State
iii) Control Flow
iv) Functions
3. What are the characteristics of an algorithm?
→ Each and every instruction should be precise.
→ Algorithm should have finite number of steps.
→ Algorithm should be written in sequence (step-by step).
→ Algorithm should have finite number of inputs.
→ Ensure that the algorithm will terminate.
→ Results should be obtained only after the algorithm terminate.
4. What are the qualities of a good algorithm?
Time: A good algorithm should take less time to execute the program.
Memory: A good algorithm should take less memory space to execute the program.
Accuracy: A good algorithm should provide more accurate results.
Sequence: A good algorithm should be written in sequence (step-by-step).
Understandability: A good algorithm should be easily understandable.
Solvability: A good algorithm should solve the problem.
5. Define Flowchart.
Flowchart is a diagrammatic representation of an algorithm. A flowchart is a picture of
the separate steps of a process in sequential order. Flowchart is made up of boxes, diamonds

39
Problem Solving and Python Programming 2020

and other shapes connected by arrows where each shape represents a step in the process. The
arrows show the order of the flow of execution.
6. What are the advantages of flowchart?
i) Better communication
ii) Efficient analysis of program
iii) Efficient coding
iv) Efficient debugging
7. What are the disadvantages of flowchart?
i) Complex logic
ii) Difficult to alter and modify
iii) Difficult to reproduce
8. Define Pseudo code.
Pseudo code is made up of two words: Pseudo and code. Pseudo means imitation and
code refers to instructions written in programming language. Pseudo code is not a real
programming language, but it looks like a programming language. It is an outline of a program,
written in a form that can be easily converted into real programming statements.
9. What are the rules for writing Pseudo code?
i) Write one statement per line.
ii) Capitalize initial keywords.
iii) End Multiline structure.
iv) Keep Statements language independent.
10. Differentiate Recursion and Iteration.
Sl.No Recursion Iteration
1 Function calls itself until the Repetition of loop until condition
base condition is reached. fails.
2 It keeps code short and It keeps the code longer.
simple.
3 It is slower. It is faster.
4 It takes more memory. It takes less memory.
5 Tracing is difficult if any Tracing is easier if any problem
problem occurs. occurs.

40
Problem Solving and Python Programming 2020

11. Write the pseudo code to calculate the sum and product of two numbers and display it.
BEGIN
INITIALIZE sum, product, number1, number2
PRINT “Input two numbers”
READ number1, number2
sum = number1 + number2
PRINT sum
COMPUTE product = number1 * number2
PRINT product
END
12. What is a function?
A function is a block of organizes, reusable code which is used to perform a task or action.
It provides better modularity. They are also called as methods, routines, procedures etc.
13. List the categories of programming languages.
Programming languages can be divided into nine major categories.
i) Interpreted Programming language
ii) Functional Programming language
iii) Compiled Programming language
iv) Procedural Programming language
v) Scripting Programming language
vi) Markup Programming language.
vii) Logic-based Programming language
viii) Concurrent Programming language.
ix) Object-Oriented Programming language.
14. Write an algorithm to accept two number’s, compute the result and print the result.
(JANUARY 2018)
1. Start
2. Read n1, n2
3. result = n1 + n2
4. Print result

41
Problem Solving and Python Programming 2020

5. Stop
15. Write an algorithm and give the flowchart to find the net salary of an employee.
Algorithm:
1. Start
2. Read the basic salary
3. If the basic is greater than or equal to 4000 ELSE Goto Step 4
4. DA= 0.32 * basic (Dearness Allowance)
5. HRA = 0.15 * basic (House Rent Allowance)
6. CCA = 325 (City Compensatory Allowance)
7. Net Salary= basic + DA HRA + CCA
8. Print Net Salary
9. Stop
16. Define Programming Language.
Programming languages are used to communicate instructions to the computer.
Programming languages are written based on syntactic and semantic rules.
17. What is control flow?
Control flow represents the order of statements execution or direction of flow of program.
There are three types of control flow
→ Sequential control flow
→ Selection control flow
→ Repetition control flow
18. Write an algorithm to find the largest of two numbers.
1. Start
2. Read a, b
3. If a is greater than b then Print “a is large”
4. Else Print “b is large”
5. Stop.

42
Problem Solving and Python Programming 2020

19. Distinguish between algorithm and program.


(JANUARY 2019)
Sl.No Algorithm Program

1 It is a well-defined, It is exact code written for


step-by-step procedure problem following all the
that allows a computer rules of the programming
to solve a problem. language.
2 Algorithms are Program allows us to
generally written in a write a code in a particular
natural language or programming language.
plain English language.

20. Write an algorithm to find the minimum number in a given list of numbers.
(JANUARY 2019)

1. Start
2. Read each elements one by one.
3. Assign the first element as the minimum.
4. Move to the next element.
5. If the current element<minimum then
Set minimum=current element
6. Repeat the Step 4 and Step 5 until the end of the list is reached.
7. Print minimum.
8. Stop.
21. How will you analyze the efficiency of an algorithm? (JANUARY 2020)
(i) Time (ii) Space
22. What is the use of Algorithm, Flowchart and Pseudo code in the perspective of problem
solving? (JANUARY 2020)
It will give finite number of clearly defined steps to derive a solution for a given problem.

43
Problem Solving and Python Programming 2020

PART B (Possible Questions)

1. What are the building blocks of an algorithm? Explain in detail.


2. Write an algorithm for the following
a. Prime number or not
b. Odd or even
c. Sum of n numbers
d. Factorial of a given number
3. Briefly describe iteration and recursion. Illustrate with an example.
4. Explain in detail Algorithmic problem solving.
5. Explain the symbols used in flow chart with basic design structure.
6. Describe pseudo code with its guidelines and examples.
7. Write an algorithm to find the sum of n even numbers.
8. i) Outline Towers of Hanoi problem. Suggest a solution to the Towers of Hanoi problem
with relevant diagrams.(8) (JANUARY 2018)
ii) Draw the flowchart to find the sum of the series 1+2+3+4+……..+100.(8)
9. i) Draw a flowchart to accept three distinct numbers, find the greatest and print the
result.(8) (JANUARY 2018)
ii) Draw a flowchart to guess a number in a range.(8)
10. i)Identify the simple strategies for developing an algorithm. (8)
ii)Write an algorithm to insert a card into a list of sorted cards.(8) (JANUARY 2019)
11. i)Discuss about the building blocks of algorithms.(8)
ii)Write a recursive algorithm to solve towers of Hanoi problem.(8) (JANUARY 2019)
12. i) What is Programming language? What are its types? Explain them in detail with their
advantages and disadvantages(8) (JANUARY 2020)
ii) Write a function find_index, which returns the index of a number in the Fibonacci
sequence, if the number is an element of this sequence and return -1 if the number is not
contained in it, call this function using user input and display the result.(8)
(JANUARY 2020)

44
Problem Solving and Python Programming 2020

13. i) What is recursive function? What are its advantages and disadvantages? Compare it
with iterative function.(6) (JANUARY 2020)
ii) Implement a recursive function in python for the sieve of Eratosthenes. The sieve of
Eratosssthenes is a simple algorithm for finding all prime numbers up to a specified integer. It
wae created by the ancient Greek mathematician Eratosthenes. The algorithm to find all prime
numbers less than or equal to a given integer n:
1)Create a list of integers from two to n:2,3,4,….n
2)start with a counter i set to 2. (i.e)the first prime number
3)starting from i+1,count up by I and remove those numbers from the
list,(i.e)2*I,3*I,4*i….
4)find the first number of the list following i.This is the next prime number
5)set I to thenumber found in the previous step
6)repeat steps 3 and 4 untill I is greater than n.
7)all the numbers,which are still in the list,are prime numbers (10) (JANUARY 2020)

PART C (Possible Questions)

1. Explain the concept of algorithm in detail.


2. Write an algorithm to sort a list of numbers in ascending order.
3. Write a pseudo code to find the sum of digits of a positive number.
4. Explain the basic symbols for constructing a flowchart & discuss about the basic
guidelines for preparing flowchart.
5. Discuss briefly about the simple strategies for developing an algorithm.
6. Write an algorithm, pseudo code and flowchart to generate the Fibonacci series. Also
state the properties of a good algorithm.
7. Summarize the difference between algorithm, flowchart and pseudo code.

45
Problem Solving and Python Programming 2020

Additional Problems

Example 1: Construct an algorithm to find the largest among three numbers.

1. Start
2. Print “Enter three numbers:”
3. Read a, b, c
4. If a > b then
i. If a > c then
print “a is largest”
ii. Else
print “c is largest”
iii. Else if b > c then
print “b is largest”
iv. Else
print “c is largest”
5. Stop
Example 2: Construct an algorithm for incrementing value of a variable that starts with initial
value 1 and stops when value becomes 5.
1. Start
2. c = 1
3. Print c
4. c = c+1
5. If c <= 5 then Goto 3
6. Stop
Example 3: Construct an algorithm to find the given year is leap year or not.
1. Start
2. Print “Enter the year:”
3. Read year
4. If year%4==0
i. Print “Leap year”
5. Else
46
Problem Solving and Python Programming 2020

ii. Print ”Not a leap year”


6. Stop
Example 4: Algorithm to convert temperature Fahrenheit to Celsius..
1. Start
2. Read temperature in Fahrenheit f
3. c =5/9*(f-32)
4. Print temperature in Celsius c
5. Stop
Example 5: Algorithm to determine a student’s average grade and indicate whether successful or
fail.
1. Start
2. Input mid-term , final
3. average=(mid-term + final)/2
4. If (average < 60)then
i. Print “Fail”
5. Else
ii. Print “Success”
6. Stop
Example 6: Algorithm to find the sum of all odd numbers between 1 and n

1. Start
2. Input n
3. Initialize sum=0, i=1
4. If i<=n goto 6
5. Else
i. sum= sum + i
6. Increment i=i+2
7. Goto 4
8. Print sum
9. Stop

47
Problem Solving and Python Programming 2020

Example 7: Algorithm to find the area of the triangle.

1. Start
2. Read a,b,c
3. s=(a+b+c)/2
4. area=sqrt(s*(s-a)*(s-b)*(s-c))
5. Print area
6. Stop
Example 8: Algorithm to compute and print the average of 10 numbers

1. Start
2. Initialize total=0, average=0
3. For 1 to 10
4. Read num
5. total = total + num
6. End For
7. Calculate average=total/10
8. Print average
9. Stop.
Example 9: Algorithm to swap two variables.

1. Start
2. Read a,b
3. Assign temp=a
4. Assign a=b
5. Assign b=temp
6. Print a,b
9. Stop.
Example 10: Write Pseudo code to determine a student whether successful or fail.

BEGIN
READ grade
IF grade>=50
48
Problem Solving and Python Programming 2020

PRINT "passed"
ELSE
PRINT "failed“
ENDIF
END
Example 11: Write Pseudo code to swap the variables.

BEGIN
SET A=0, B=0, C=0
READ A, B, C
C=A
A=B
B=C
PRINT A, B
END
Example 12: Write Pseudo code to check whether the given number is odd or even.

BEGIN
READ number
IF number%2=0 THEN
DISPLAY “Number is Even”
ELSE
DISPLAY “Number is Odd”
ENDIF
END
Example 13: Write Pseudo code to print the numbers from 1 to 100.

BEGIN
READ i
INITIALISE i=1
WHILE i <=100
DISPLAY i

49
Problem Solving and Python Programming 2020

INCREMENT i=i+1
ENDWHILE
END
Example 14: Pseudo code for computing the area of a rectangle.

BEGIN
READ height
READ width
COMPUTE area=height * width
PRINT area
END
Example 15: Pseudo code for computing the average of five numbers.

BEGIN
PRINT “Enter 5 numbers”
READ n1, n2, n3, n4, n5
PRINT “The average is”
SET avg=(n1+n2+n3+n4+n5)/5
PRINT avg
END
Example 16: Write Pseudo code to check whether the given number is positive or negative.

BEGIN
READ number
IF number > 0 THEN
DISPLAY “Number is Positive”
ELSE
DISPLAY “Number is Negative”
ENDIF
END
Example 17: Write Pseudo code to check whether the given year is leap year or not.

BEGIN
50
Problem Solving and Python Programming 2020

READ year
IF year %4 = 0 && year %100!=0 && year % 400 =0 THEN
DISPLAY “Leap Year”
ELSE
DISPLAY “Not a Leap Year”
ENDIF
END

Example 18: Flowchart representation to print 1 to 20.

Start

Initialize x=0

Increment x = x+ 1

Print x

Yes
If x<
20

No

Stop

51
Problem Solving and Python Programming 2020

2
Example 19: Flowchart representation to find all the roots of a quadratic equation ax +bx+c=0

Start

Read a, b, c, d, x1, x2, rp ,ip

D= b-4ac

True False
Is

D>=0?

r1=(-b+sqrt(D))/2a ip= -b/2a

r2=(-b-sqrt(D))/2a rp =sqrt(D)/2a

x1 =rp+ j ip

x2=rp- j ip

Display r1 , r2

Stop

52
Problem Solving and Python Programming 2020

Example 20: Flowchart representation to find the Fibonacci series till term≤1000.

Start

Read sterm, fterm, temp

fterm=0, sterm= 1

False
Is
sterm<=1000?

True

Display sterm

temp=sterm

sterm=sterm+fterm

fterm=temp Stop

53
Problem Solving and Python Programming 2020

Example 21: Flowchart representation to find whether the given number is odd or even.

Start

Read n

No If Yes

n%2==0

Print “Odd” Print “Even”

Stop

54
Problem Solving and Python Programming 2020

CHAPTER 2

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

55
Problem Solving and Python Programming 2020

56
Problem Solving and Python Programming 2020

DATA, EXPRESSIONS, STATEMENTS


2. PYTHON INTRODUCTION
Python is a general purpose interpreted, object oriented, interactive, high level
programming language. It was developed by “GUIDO VAN ROSSUM” in 1991 at the National
Research Institute for Mathematics and Computer Science in Netherlands. Many of the python
features are originated from an interpreted language called ”ABC”. In order to overcome the
limitations in ABC, Python language was developed. Since the developer was the fan of the BBC
comedy show “Monty Pythons Flying Circus”, he named the language as “PYTHON”.
Features of Python:
Easy to learn: Python is a simple programming language with few keywords, simple syntax
which is easy to learn.
Interpreted: Python is processed at runtime by the interpreter.
Interactive: We interact with interpreter directly to write our programs.
Object oriented: Python program is built around objects which combine data and
functionalities.
High level language: When writing a program, no need to bother about the low level details
such as managing memory etc.
Simple: It is a simple language. Reading a Python program feels like reading English.
Portable: Python can run a variety of platforms.
Free and open source: We can freely distribute copy of Python software.
Extendable: We can add low level modules to the Python interpreter easily.
Easy to maintain: Python source code is easy to maintain.
2.1 PYTHON INTERPRETER AND INTERACTIVE MODE
Python is an interpreted programming language, because Python programs are executed
by the python interpreter. Interpreter takes high level program as input and executes the program.
Interpreter processes the source program without translating it into a machine language at a
minimum time. It read lines and performs computations alternatively. The diagrammatic
representation of Python interpreter mode is given below.

57
Problem Solving and Python Programming 2020

Source code
Output
Python
data
Interpreter
Input data

Fig 2.1: Interpreter


Compiler:
Compiler reads the entire source program and translates it to machine readable form
called object code or executable code. Once a program in compiled, the program can be executed
repeatedly without further translations.

Source code Compiler Machine code

Input data Executable Output data


program

Fig 2.2: Compiler


Difference between interpreter and compiler:
Sl.No Interpreter Compiler

Scans the entire program and translates


1 Translate program one statement at a time
the whole into machine code

2 No intermediate code is generated Generates intermediate code

3 Execution is slower Execution is faster

4 It require less memory It require more memory

5 Example: Python Example: C,C++

58
Problem Solving and Python Programming 2020

There are two different modes to use the interpreter.


→Interpreter mode (or) Script mode.
→Interactive mode.
2.1.1 Python interpreter mode
Python interpreter mode is a mode, where scripted and finished .py files are run in the
python interpreter. The Python file is stored in the extension (.py). Python programs can be
executed in the following methods.
i)Using command line window
ii)Using python’s IDLE
iii)Directly from command prompt
i) Using command line window
The following steps are followed to use the command line window.
→Open command line window
→At the >>>prompt, type the following
print “HELLO PYTHON”
→Press enter
→To exit from python, type the following.
exit.
ii) Using python’s IDLE
IDLE (Integrated Development and Learning Environment) is a tool, which is included in
Python’s installation package. If we click the IDLE icon, it open the following python shell
window.

59
Problem Solving and Python Programming 2020

iii) Directly from command prompt


The following steps are followed to use the command prompt.
→Open text editor to write the program.
→Type and save it by filename.py
→Open command prompt, type the name of the program.
→Press enter.

2.1.2 Python interactive mode


Python interactive mode is a command line shell which gives immediate feedback for
each statement. We interact with Python interpreter to write a program. Here the execution is
convenient for smaller programs. In interactive mode, we do the following steps.
→User type the expression.
→Immediately expression is executed.
→Result is printed.

60
Problem Solving and Python Programming 2020

2.2 VALUES AND TYPES


Values:
Values are the basic units of data, like a number or a string that a program manipulates.
Example: 2,’Hello World’. These values belong to different data types. That is 2 is an integer
data type and Hello World is a string data type.
Types/ Data types:
A type is a category of values. Integers(type int),floating point(type float),Booleans(type
bool),strings(type str) and lists ,tuples, dictionaries are predefined data types in python. They are
called built-in data types.

Data types

Numbers None Sequence Sets Mappings

1. Complex 1. Strings
2. Integer
3. Floating 2. Tuples Dictionary
point 3. Lists
4. Boolean
Fig 2.3: List of data types in Python
2.2.1 Integer (type int)
An integer data type represents the whole numbers. It represents positive and negative
numbers. Integer data type have unlimited size in Python.
Example: -3, 2 etc
Types of integer data type:
i) Regular integer
ii) Binary literals (base 2)
iii) Octal literals (base 8)
iv) Hexa decimal literals (base 16)

61
Problem Solving and Python Programming 2020

i) Regular integer
They are normal integers.
Example:
>>>a=9293
>>>b= -136
ii) Binary literals (base 2)
A binary literal is of the form zero followed by an uppercase B or lowercase b. The
literals are 0 and 1.
Example:
>>>bin=0b1111
>>>print(bin)
Output:
15
iii) Octal literals (base 8)
An octal literal is a number prefixed with zero followed by either uppercase O or lower
case o. The literals are 0 to 7.
Example:
>>>oct=0O24
>>>print(oct)
Output:
20
iv)Hexa decimal literals (base 16)
A hexa decimal literal is prefixed by 0(zero) followed by an upper case X or a lower case
x. The literals are 0 to9, [a-f/A-F].
Example:
>>>hex=0x9A
>>>print(hex)
Output:
154

62
Problem Solving and Python Programming 2020

2.2.2 Floating point numbers (type float)


Numbers with fractions or decimal points are called floating point numbers. Floating
point data type is used to represent scientific notations where the upper case ‘E’ or lower case ‘e’
signifies the 10th power.
Example 1: Example 2: Example 3:
>>>3.3e3 >>>112.9e2 >>>c=2.1
3300.0 11290.0 >>>type(c)
<type ‘float’>
2.2.3 Boolean (type bool)
Boolean data type was found by George Boole(1815-1864).It takes 2 values(True or
False).These two values are used when evaluating comparisons, conditional expressions etc. The
common way to produce boolean value is relational operator. The various relational operators
used in python are <,>, <=,>= etc.
Example 1: Example 2: Example 3:
>>>3<4 >>>a= (3>4) >>>a= (3>4)
True >>>a >>>a
False >>>type(a)
<type ‘bool’>
2.2.4 Strings (type str)
String is defined as collection of characters which may consist of letters, numbers and
special symbols or a combination of these types within quotes. An individual character in a string
is accessed using an index. The index should always be an integer (positive or negative). An
index starts from 0 to n-1. Strings are immutable i.e. the contents of the string cannot be changed
after it is created. Python will get the input at run time by default as a string. Python treats single
quotes is same as double quotes.eg: ’hello’ or “hello”.
String operators:
X holds python and Y holds program.

63
Problem Solving and Python Programming 2020

Operator Description Example

>>>X+Y
+ Concatenation-Adds values of 2 strings
python program

Repetition-creates new string.(i.e.)concatenate multiple >>>X*2


*
copies of same string python python

>>>x[0:3]
[] Slice-Gives the character from the given range.
pyt

>>>x[1:2]
[:] Range slice-Give the characters from the given range.
y

Membership-returns true if a character exists in the >>>t in X


in
given string. true

Membership-returns true if a character not exists in the >>>m not in X


not in
given string. true

Built-in string methods:


→capitalize()-This function capitalizes the first letter of a string.
→islower()-It returns true, if all the characters in given string are lower case
→isupper()-It returns true, if all the characters in given string are upper case.
→len(string)-Returns the length of the string.
→lower()-Convert all upper case letters to lower case letters.
Example Program:
>>>str=”HelloPython”
>>>print str
HelloPython
>>>print str[0]
H
64
Problem Solving and Python Programming 2020

>>>print str[0:3]
Hel
>>>print str[5:]
Python
>>>print str*2
HelloPython HelloPython
>>>print str+”welcome”
HelloPython welcome
2.2.5 Lists
List data type contains elements of various data types. Values in a list are called elements
or items of list. The list is enclosed by square brackets [ ], where items are separated by commas.
List values can be accessed using slice operator ([] or [:]) .The index 0 represents beginning of
the list and -1 represents ending of the list.
→ list[0] represents beginning of list.
→ list[-1] represents ending of list.
Syntax:
listname= [value1,value2,…value n]
Example:
>>>mylist = [10, 10.5, ‘programming’]
Example Program:
>>>mylist= ()
>>>mylist=[‘python’,10,10.5,’program’]
>>>print mylist
[‘python’,10,10.5,’program’]
>>>print mylist[1:3]
[10, 10.5]
>>>print mylist[2:]
[10.5,’program’]
>>>print mylist*2
[‘python’,10,10.5,’program’,’python’,10,10.5,’program’]

65
Problem Solving and Python Programming 2020

>>>print mylist[-1]
[‘program’]
2.3 VARIABLES
Variable is a name that is assigned to a value. The value can be changed during execution
of a program. While creating a variable, memory space is reserved in memory. Based on the data
type of a variable, the interpreter allocates memory.
Syntax: variable name=value
Example: price=20
2.3.1 Rules for naming variables
→Variable name can be any length.
→They can contain both letters and numbers. But they cannot begin with numbers.
→Both upper case and lower case letters are used.
→Variable names are case sensitive.
Example: midname, midName, MidName are different variables.
→Variable name cannot be any one of the keywords.
2.3.2 Assigning values to variables
The equal (=) sign is used to assign the values to variables.
→Left of = operator is the name of the variable.
→Right of = operator is the value of variable.
Example:
>>>X=5
>>>name=”Python”
>>>print X
5
>>>print name
Python
In the above program X and name are variables. The value of X is 5 and the value of name is
Python.

66
Problem Solving and Python Programming 2020

2.4 EXPRESSIONS
Expression is a combination of values, variables, operators and operands. A value itself is
considered as an expression.
Example:
17 #expression
x #expression
x+17 #expression
Expression consists of combination of operators and operands.
Example:
5+ (8*k) #expression
The above expression consists of 2 sub expressions. That is 5 and (8*k).Here sub expression
(8*k) is evaluated first.
Evaluation of expressions:
When expression is typed at the prompt, the interpreter evaluates it, and finds the value of
expression.
Program:
>>>12+8 #expression
20
>>>n=100 #expression
>>>print(n) #expression
100
>>>100 #expression
100
2.5 STATEMENTS (or) I/O STATEMENTS
Statement is a section of code (or) instruction that represents a command (or) action.
2.5.1 Types of statements
i) Assignment statements
ii) Simultaneous assignment statements
iii) Input statements
iv) Print statements

67
Problem Solving and Python Programming 2020

i)Assignment statements
Assignment statements assigns right of = symbol to left of = symbol.
Example:
>>>Name=’CSE’
>>>age=100
>>>Name
CSE
>>>age
100
ii) Simultaneous assignment statements
Simultaneous assignment statement is used to assign more number of values to more
variables simultaneously.
Example:
>>>x,y=10,20
>>>x
10
>>>y
20
>>>sum, diff=x+y, y-x
>>>sum
30
>>>diff
10

iii) Input statements


In input statements ‘input’ function is used to get the input from user.
Example:
>>>Name=input (“Enter the Name :”)
Enter the Name: CSE
>>>Name
CSE
68
Problem Solving and Python Programming 2020

>>>Age=input (“Enter the age :”)


Enter the age: 100
>>> Age
100
iv) Print statements
Here ‘print’ function is used to print values to screen. It takes a series of values are
separated by commas.
Example:
>>>Name=input (“Enter the Name :”)
Enter the Name: Jovitha
>>>print (‘Hello’, Name)
Hello Jovitha
>>>print (‘Welcome’, Jovitha)
Welcome Jovitha
>>>print (‘Hello \n’,Name)
Hello
Jovitha
2.6 TUPLE ASSIGNMENT
Tuple is an immutable sequence of values. (i.e.) we cannot change the elements of
tuples. Tuples are created by using parenthesis ().Tuple is an ordered collection of values of
different data types. Tuple values are indexed by integers.
Example:
>>>t=(‘a’,’b’,’c’)
>>>t
(‘a’,’b’,’c’)
Tuple assignment is an assignment with tuple of variables on left side and tuple of expressions
on right side.
>>> X, Y, Z=100, -45, 0
>>> print X, Y, Z
100 -45 0

69
Problem Solving and Python Programming 2020

Here left side is a tuple of variable. The right side is a tuple of expression.
2.6.1 Working of tuple assignment
i) The first variable in the tuple of left side is assigned to first expression in tuple of right side.
ii) Similarly, the second variable in the tuple of left side is assigned to second expression in
tuple of right side. Number of variables on left side and the number of expressions on the right
side must be same.
Example: Program on tuple assignment
>>>#empty tuple
>>>mytuple=( )
>>>mytuple
()
>>>#tuples having same datatypes
>>>mytuple=(1,2,3,4,5)
>>>mytuple
(1, 2, 3, 4, 5)
>>>#tuples having different datatypes
>>>mytuple=(1,”Python”,2.5)
>>>mytuple
(1,”Python”, 2.5)
>>>#tuple assignment
>>>X, Y, Z= mytuple
>>>X
1
>>>Y
Python
>>>Z
2.5

70
Problem Solving and Python Programming 2020

2.7 PRECEDENCE OF OPERATORS


Operator:
An operator is a special symbol that is used to perform particular mathematical or logical
computations like addition, multiplication, comparison and so on. The value of operator is
applied to be called operands. For e.g., in the expression 4 + 5, 4 and 5 are operands and + is an
operator. The following tokens are operators in Python:

+ - * ** / // %

<< >> & | ^ ~ <>


< > <= >= == !=

Operator precedence:
When an expression contains more than one operator, precedence is used to determine
the order of evaluation. The order of evaluation depends on rules of precedence.
2.7.1 Rules of precedence
i) Parenthesis has the highest precedence.
Example: 5*(9-3)
Here expression in parenthesis is evaluated first.
ii) Exponentiation has next highest precedence.
Example: 1+2**3=9
iii) Multiplication and division have next higher precedence than addition and subtraction.
Example: 3*2-1=5
iv) Operators with same precedence are evaluated from left to right (Except exponentiation).
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

71
Problem Solving and Python Programming 2020

[expressions...] list display


{ key: value...} dictionary display

x[index:index] Slicing
left to right

** Exponentiation right-to-left
+x Unary plus
-x Unary minus left to right
~x Bitwise NOT
* Multiplication
/ Division
left to right
// 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
is, is not
Identity tests Chain from left to right
<, <=, >, >=, <>, !=,
Comparisons
==
not Boolean NOT left to right
and Boolean AND left to right
or Boolean OR left to right

→The acronym PEMDAS is useful way to remember the rules. That is,
P (parenthesis first)
72
Problem Solving and Python Programming 2020

E (Exponent)
MD (multiplication and division)
AS (addition and subtraction)
→Arithmetic evaluation is carried out using two phases from left to right. During the first phase
highest priority operators are evaluated. The second phase lowest priority operators are
evaluated.
Example:
6+4/2 is 8, not 5.
Example:
>>>X, Y, Z=2, 3, 4
>>>value=X-Y/3+Z*3-1
>>>print(“Result=”,value)
Result=12
2.8 COMMENTS
Comments are the non-executable statements explain what the program does. For large
programs it often difficult to understand what is does. The comment can be added in the program
code with the symbol #.
Comment contains information for persons reading the program. Comment lines are
ignored during program execution. Comment lines have no effect on the program results.
Example:
print ‘Hello, World!’ # print the message Hello, World!; comment
v=7 # creates the variable v and assign the value 7; comment
2.8.1 Types of comments
i) Single line comments
ii) Multi line comments
i) Single line comments
Single line comments describes information in one line(short),and they start with the
symbol #.Everything from the # to the end of the line is ignored, it has no effect on the execution
of the program.

73
Problem Solving and Python Programming 2020

Example:
>>>#This is a print statement
>>>print(“Hello python”)
Hello python
ii) Multi line comments
Multi line comments describes information in detail (multiple line).Here,more than
one line of comments can be added to the program in between the triple quotes(” ” ”).
Example:
”””This is print statement
This line print “Hello python”
Written by ABC, April 2017”””
2.9 MODULES AND FUNCTIONS
2.9.1 Modules
Module is a file containing python definitions and statements. We use modules to break
down large programs into small manageable and organized files. Modules provide reusability of
code. Modules are imported from other modules using the import command.
i) When module gets imported, Python interpreter searches for module.
ii) If module is found, it is imported.
iii) If module is not found,”module not found” will be displayed.

Modules

Built-in modules User defined modules

random math date time

Fig 2.4: Types of modules

74
Problem Solving and Python Programming 2020

Built -in modules:


Built-in modules are predefined modules, which is already in Python standard library.
Python have the following built-in modules.
i) random
This module generates random numbers. If we want random integer, we use randint
function.
Example:
>>>import random
>>> print random. randint(0,5)
1 (or) 2 (or) 3 (or) 4 (or)5
ii) math
This module is used for mathematical calculations. If we want to calculate square root,
we use the function sqrt.
Example:
>>>import math
4
>>>math . factorial(4)
24
iii) datetime
This module is used to show the current date and time.
Example:
>>>import datetime
>>>datetime . time()
9:15:20
>>>datetime . date()
21.06.2018
User defined modules:
In user defined modules we do the following steps. To create module, write one or more
functions in file, then save it with .py extensions.
i) Create a file
def add(a,b):

75
Problem Solving and Python Programming 2020

c=a+b
return c
ii) Save it as sum.py
iii) Import the module using import command
>>>import sum
>>>print sum.add(10,20)
2.9.2 Functions
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.
Function is defined as a block of organized, reusable code that is used to perform single,
related action. Function provides better modularity and high degree of reusing.
Advantages of using functions:
i) Better modularity
ii) High degree of reusing
iii) Better readability
iv) Easy to debug and testing
v) Improved maintainability

Functions

User Defined Built-in functions


Functions

Fig 2.5: Types of functions

76
Problem Solving and Python Programming 2020

Built-in Functions:
Built-in functions are predefined functions. User can use the functions but cannot
modify them. Python has the following built-in functions.
i) input():read the input from user.
>>>name=input (“Enter the name”)
ii) print():print values to screen.
>>>print (“Hello python”)
iii) type():gives the type of value.
>>>type (12)
<type ‘int’>
iv)min():find minimum value from several values.
>>>min (5,7,8,9)
5
v) max():find maximum value from several values.
>>>max (10,100,50,70)
100
vi) pow():find power of given value.
>>>pow (3,2)
9
User defined functions:
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()
Elements of user defined functions:
(i)Function definition
(ii)Function-Use (or) function call

77
Problem Solving and Python Programming 2020

2.10 FUNCTION DEFINITION AND USE


2.10.1 Function definition
Functions in Python are defined using the block keyword def followed by the function
name and parenthesis ( ). Function definition includes:
(i) A header, which begins with a keyword def and ends with a colon.
(ii) A body follows function header, consisting of one or more python statements.
Syntax:
def functionname( parameters ): #Function header
statements #Function body
return(expressions)
2.10.2 Function use
Function call is a statement that runs a function. It consists of function name followed
by argument list in parenthesis. Function is used by function call.
Syntax:
functionname(arguments)
Example Program:
def sum(a,b):
c=a+b
return c
print(“The sum is:”, sum(10,5))
Output:
The sum is:15
In the above program sum function return the sum values of two numbers, that can be used
anywhere in the program. The return statement is used to return values from functions.
2.11 FLOW OF EXECUTION
Flow of execution is the running order of statements. A function should be defined before
its first use. The execution always begins at the first statement of the program. Statements are run
one at a time, in the order from top to bottom. Function definition does not alter the flow of
execution of program. Statements inside function definition do not run until function is called. In
flow of execution statements are executed in order.
78
Problem Solving and Python Programming 2020

Example Program:
1. def sum(a,b):
2. c=a+b
3. return c
4. print(“The sum is:”, sum(10,5))
Python interpreter starts at line 1 of above program. In line 1, there is a function
definition. So it skips the function definition, and go to line 4.In line 4, function call is present.
So it goes back to function definition and execute it. After return statement, it again comes to
line 4 and execute it.
2.12 ARGUMENTS AND PARAMETERS
2.12.1 Arguments
Argument is the value, supply to function call. This value is assigned to corresponding
parameter in the function definition. Arguments are specified within a pair of paranthesis,
separated by commas.
2.12.2 Types of arguments
i) Required arguments
ii) Keyword arguments
iii) Default arguments
iv) Variable-Length arguments
i) Required arguments
Required arguments are the arguments passed to a function in correct positional order.
Here number of arguments in function call should match exactly with function definition.
Example Program:
def sum(a,b):
c=a+b
return c
print(“The sum is:”,sum(6,4))
Output:
The sum is:10

79
Problem Solving and Python Programming 2020

ii) Keyword arguments


The keyword arguments are related to function call. Here caller identifies arguments by
parameter name.
Example Program:
def sum(a,b):
c=a+b
return c
print(“The sum is:”,sum(a=5,b=10))
Output:
The sum is:15
iii) Default arguments
Default argument is an argument that assume default value if value is not provided in
function call.
Example Program:
def sum(a,b):
c=a+b
return c
print(“The sum is:”,sum(a=5))
Output:
The sum is:15
iv)Variable-Length arguments
Variable-Length arguments are arguments that makes function call with any number of
arguments. Here (*) is placed before the name of the variable.
Example Program:
def greeting(*name):
print(“Hai”,name)
greeting(“Welcome”)
greeting(“Welcome”,”Hello”)
Output:
Hai Welcome

80
Problem Solving and Python Programming 2020

Hai Welcome Hello


2.12.3 Parameter
Parameter is the name given in the function definition. Parameters are specified within
the pair of parenthesis. Parameters are just like a variable.
Syntax:
def functionname(parameter1,parameter2):
statements
functionname(argument1,argument2)
Example Program:
def sum(a,b):
c=a+b
return c
print(“The sum is:”,sum(6,4))
Output:
The sum is: 10
In the above example, parameter‘s are a, b. The argument values are 6, 4. Here sum function is
defined with 2 parameters to find sum of 2 numbers. In the function call, we need to pass 2
arguments.
2.13 ILLUSTRATIVE PROGRAMS
2.13.1 Exchange the values of two variables
Without using temp function:
def swap(a,b):
a,b=b,a
print(“After Swap:”)
print(“First number:”,a)
print(“Second number:”,b)
a=input(“Enter the first number:”)
b=input(“Enter the second number:”)
print(“Before Swap: ”)
print(“First number:”,a)

81
Problem Solving and Python Programming 2020

print(“Second number:”,b)
swap(a,b)
Output:
Enter the first number: 20
Enter the second number: 10
Before Swap:
First number: 20
Second number: 10
After Swap:
First number: 10
Second number: 20
Using temp function:
n1=input (“Enter the value of a:”)
n2=input (“Enter the value of b:”)
print (“Before Swap:”)
print (“Value of a:”,n1)
print (“Value of b:”,n2)
temp =n1
n1=n2
n2=temp
print(“After Swap:”)
print(“Value of a:”,n1)
print(“Value of b:”,n2)
Output:
Before Swap:
Value of a: 10
Value of b: 15
After Swap:
Value of a: 15
Value of b: 10

82
Problem Solving and Python Programming 2020

2.13.2 Circulate the values of n variables


def rotate(L,n):
newlist=L[ n: ]+L[ :n ]
return newlist
list = [1,2,3,4,5]
print(“The original list is:”,list)
mylist=rotate(list,1)
print(“List rotated clockwise by 1:”,mylist)
mylist=rotate(list,2)
print(“List rotated clockwise by 2:”,mylist)
mylist=rotate(list,3)
print(“List rotated clockwise by 3:”,mylist)
mylist=rotate(list,4)
print(“List rotated clockwise by 4:”,mylist)
Output:
The original list is: [1, 2, 3, 4, 5]
List rotated clockwise by 1: [2, 3, 4, 5, 1]
List rotated clockwise by 2: [3, 4, 5, 1, 2]
List rotated clockwise by 3: [4, 5, 1, 2, 3]
List rotated clockwise by 4: [5, 1, 2, 3, 4]
2.13.3 Distance between two points
import math
def distance(x1,y1,x2,y2):
dx=x2 - x1
dy=y2 - y1
dsquare=dx**2 - dy**2
result=math . sqrt(dsquare)
return result
x1=int(input(“Enter the value of x1:”))
y1=int(input(“Enter the value of y1:”))

83
Problem Solving and Python Programming 2020

x2=int(input(“Enter the value of x2:”))


y2=int(input(“Enter the value of y2:”))
print(“The distance between two points:” ,distance(x1,y1,x2,y2))
Output:
Enter the value of x1:2
Enter the value of y1:4
Enter the value of x2:3
Enter the value of x1:6
The distance between two points:2.23

84
Problem Solving and Python Programming 2020

PART A (2 Marks with Answers)


1. Write short notes on python.
Python is a general-purpose, interpreted, interactive, object-oriented, and high-level
programming language. Python is created by “Guido Van Rossum” in 1991. It is derived from
several languages, including ABC, Modula-3, C, C++, Algol-68, Smalltalk, and Unix shell and
other scripting languages.
2. Compare interpreter and compiler.
Sl.No Interpreter Compiler

Translate program one statement at a Scans the entire program and translates the
1
time. whole into machine code.

2 No intermediate code is generated. Generates intermediate code.

3 Execution is slower. Execution is faster.

4 It require less memory It require more memory

5 Example: Python Example:C,C++

3. What are the advantages and disadvantages of Python?


Advantages:
→Python is easy to learn for even a novice developer
→Supports multiple systems and platforms.
→Object Oriented Programming-driven
→Allows to scale even the most complex applications with ease.
→A large number of resources are available for Python.
Disadvantages:
→Python is slow.
→Have limitations with database access.
→Python is not good for multi-processor/multi-core work.
4. Define operator.
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

85
Problem Solving and Python Programming 2020

values the operator is applied to are called operands. For eg, in the expression 4 + 5, 4 and 5 are
operands and + is an operator.
5. What is the difference between * operator and ** operator?
* is a multiplication operator which multiplies two operands.
Example: 3*2 returns 6.
** is an exponent operator that performs exponential (power) calculation.
Example: 3**2 returns 9.
6. Compare arguments and parameters.
Arguments Parameters
1.It is the value, which is given to 1.It is the name, which is given in
function call. function definition.
2.Syntax: 2.Syntax:
functionname(arguments) def functionname(parameter):

7. What is the difference between = and == operator?


= is an assignment operator and = = is a relational operator.
= = operator returns true, if the values of two operands are equal.
= operator assigns values from right side operand to left side operand.
8. Define flow of execution in python.
Flow of execution is the order of statements run-in. A function should be defined before
its first use. The execution begins at first statements of program.
9. What are the comment lines in Python?
Comments are the non-executable statements explain what the program does. For large
programs it often difficult to understand what is does. The comment can be added in the program
code with the symbol #.Comment contains information for persons reading the program.
Comment lines are ignored during program execution. Comment lines have no effect on the
program results.
Example:
print ‘Hello, World!’ # print the message Hello, World!; comment
v=7 # creates the variable v and assign the value 7; comment

86
Problem Solving and Python Programming 2020

10. What is the need of operator precedence?


When expressions contain more than one operator, precedence is used to determine the
order of evaluation. The order of evaluation depends on rules of precedence. The rules are,
(i) Parenthesis has the highest precedence.
(ii) Exponentiations have next highest precedence.
(iii) Multiplication and division have higher precedence than addition and subtraction
(iv)Operators with same precedence are evaluated from left to right (except
exponentiation).
11. Write the syntax of function definition.
Functions in python are defined using the block keyword def followed by the function
name and parentheses ( ).Function definition includes:
(i) A header, which begins with a keyword def and ends with a colon.
(ii) A body follows function header, consisting of one or more python statements.
Syntax:
def functionname( parameters ): #Function header
statements #Function body
12. Define keyword. List few Python keywords.
Keywords are certain reserved words that have standard and pre-defined meaning in
python. We cannot use a keyword as variable name, function name or any other identifier.
Example: False, class, finally, nonlocal, yield, lambda, assert.
14.What is a variable?
Variable is a name that is assigned to a value. The value can be changed during execution
of a program. While creating a variable, memory space is reserved in memory. Based on the data
type of a variable, the interpreter allocates memory.
Syntax: variable name=value
Example: price=20
15.What is RETURN statement?
It is used to return the control from calling function to the next statement in the program.
It can also return some values.
Example: return, return 0, return (a+b)

87
Problem Solving and Python Programming 2020

16. Define function.


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. Built-in functions, user defined functions are the two
types of functions.
17.How tuple is assigned in python.
Tuple assignment is an assignment with tuple of variables on left side and tuple of
expression on right side.
>>> X,Y,Z=100, -45, 0
>>>print X,Y,Z
100 -45 0
Here left side is a tuple of variable. The right side is a tuple of expression
18. Write short notes on strings.
String is defined as collection of characters which may consist of letters, numbers, and
special symbols or a combination of these types within quotes. Python treats single quotes is
same as double quotes.eg: ’hello’ or “hello”.
19. What are pre-defined functions? Give example.
Pre-defined functions or Built-in functions are functions already built into Python
interpreter and are readily available for use.
Example: print(), abs(), len()
20. Write in short about relational operators.
Relational operators are used to compare any two values. An expression which uses a
relational operator is called a relational expression. The value of a relational expression is either
true or false.
Example: = =, !=,>, <
3>4
Output: False
21. What are the Bitwise operators available in Python?
& - Bitwise AND
| - Bitwise OR

88
Problem Solving and Python Programming 2020

~ - One’s Complement
>> - Right shift
<< - Left shift
^ - Bitwise XOR
22. What are the features of the Python language?
→Easy to learn
→Interpreted
→Interactive
→Object Oriented
→High Level language
23. Name four types of scalar objects in python has. (JANUARY 2018)
The commonly used scalar types in Python are:
Int- Any integer.
Float-Floating point number (64 bit precision).
Bool-True, False.
Str-A sequence of characters.
24.What is tuple? How literals of type tuple are written? Give example (JANUARY 2018)
Tuple is an immutable sequence of values, they are separated by commas. The value can
be any type and they are indexed by integer. The literals of type tuple are written as,
(), (9,), (8, 9, 0)
25. What are keywords? Give example. (JANUARY 2019)
The python interpreter uses keywords to recognize the structure of the program and they
cannot be used as variable names.Python2 has 31 keywords. Example: class, print
26. State the reason to divide programs into functions. (JANUARY 2019)
Creating a new function gives an opportunity to name a group of statements, which
makes program easier to read and debug. Functions can make a program to smaller by
eliminating the repeated code.

89
Problem Solving and Python Programming 2020

27. Compare interpreter and compiler. What type of translator is used for Python?
(JANUARY 2020)
Interpreter - Translates program one statement at a time Compiler - Translates program one
statement at a time. Python uses interpreter as a translator
28. Write a python program to print sum of cubes of the values of n variables.
(JANUARY 2020)
n=int(input())
sum=0
for i in range(1,n+1):
sum=sum+i**3
print(sum)

90
Problem Solving and Python Programming 2020

PART-B (Possible Questions)

1. Briefly discuss about the fundamental of python.


2. i) List some features of python.
ii) Explain about the input and output functions used in python.
3. i) Differentiate interactive mode and script mode.
ii) Explain operator precedence with suitable examples.
4. Define function. Explain the scope and lifetime of the variables with suitable examples.
5. Explain the various function arguments in detail.
6. Explain python modules in detail. Explain some of the built-in modules available in python.
7. Explain how variable is named and assigned in python.
8. Write a python program to exchange values of 2 variables without using functions.
9. Explain in detail about various literals used in python.
10. Write a python program to circulate values of n variables.
11. Write short notes on comments.
12. Write a python program to calculate distance between two points.
13. i )What is numeric literals? Give examples (4) (JANUARY 2018)
ii) Appraise the arithmetic operators in python with an example. (12)
14. i) Outline the operator precedence of arithmetic operators in python.(6) (JANUARY 2018)
ii)Write a python program to exchange the values of 2 variables.(4)
iii)Write a python program using function to find the sum of first ‘n’ even numbers and print
the result . (6)
15.i) Sketch the structure of interpreter and compiler. Detail the difference between them.
Explain how python works in interactive mode and script mode with example. (2+2+4)
ii)Summarize the precedence of mathematical operators in python.(8) (JANUARY 2019)
16.i)Explain the syntax and structure of user defined functions in python with examples. Also
discuss about parameter passing in function. (12)
ii)Write a python function to swap the values of two variables.(4) (JANUARY 2019)
17.i)Write a python program to rotate a list by right n times with and without slicing
techniques(4+4) (JANUARY 2020)

91
Problem Solving and Python Programming 2020

ii)Discuss about keyword arguments and default arguments in python with examples(4+4)
(JANUARY 2020)
18.i)Write a python program print the maximum among ‘n’randomly generate ‘d’ numbers by
storing them in a list(10) (JANUARY 2020)
ii)Evaluate the following expression in python
(i)24//6%3
(ii)float(4+int(2.39)%2)
(iii)2 **2**3 (6) (JANUARY 2020)

92
Problem Solving and Python Programming 2020

PART – C (Possible Questions)

1. Explain how to write and execute a program in python illustrate the steps for writing a python
program to check whether the number is palindrome or not.
2. Formulate with an example program to pass the list arguments to a function.
3. Do the Case study and perform the following operation in tuples i) Maxima ii) minima iii) sum
of two tuples iv) duplicate a tuple v) slicing operator vi) obtaining a list from a tuple vii)
Compare two tuples viii) printing two tuples of different data types.
4. Formulate with an example program to find out all the values in the list that is greater than the
specified number.
5. Write a program to find out the square root of two numbers.

93
Problem Solving and Python Programming 2020

Additional Programs
1. Python program to calculate the average of numbers in a given list.
n=int(input("Enter the number of elements to be inserted: "))
a=[]
for i in range(0,n):
elem=int(input("Enter the element: "))
a.append(elem)
avg=sum(a)/n
print("Average of elements in the list",round(avg,2))
Output:
Enter the number of elements to be inserted: 3
Enter the element: 23
Enter the element: 45
Enter the element: 56
Average of elements in the list 41.33
2. Python program to exchange the values of two numbers without using a temporary
variable.
def swap(a,b):
a,b=b,a
print(“After Swap:”)
print(“First number:”,a)
print(“Second number:”,b)
a=input(“Enter the first number:”)
b=input(“Enter the second number:”)
print(“Before Swap: ”)
print(“First number:”,a)
print(“Second number:”,b)
swap(a,b)
Output:
Enter the first number: 20

94
Problem Solving and Python Programming 2020

Enter the second number: 10


Before Swap:
First number: 20
Second number: 10
After Swap:
First number: 10
Second number: 20
3. Python program to reverse a given number.
n=int(input("Enter number: "))
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
print("Reverse of the number:",rev)
Output:
Enter number: 124
Reverse of the number: 421
4. Python program to check whether a number is positive or negative.
a=int(input("Enter number: "))
if(a>0):
print("Number is positive")
else:
print("Number is negative")
Output:
Enter number: 45
Number is positive
5. Python program to take in the marks of 5 subjects and display the grade.
sub1=int(input("Enter the marks of first subject: "))
sub2=int(input("Enter the marks of second subject: "))

95
Problem Solving and Python Programming 2020

sub3=int(input("Enter the marks of third subject: "))


sub4=int(input("Enter the marks of fourth subject: "))
sub5=int(input("Enter the marks of fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=90):
print("Grade: A")
elif(avg>=80&avg<90):
print("Grade: B")
elif(avg>=70&avg<80):
print("Grade: C")
elif(avg>=60&avg<70):
print("Grade: D")
else:
print("Grade: F")
Output:
Enter the marks of first subject: 85
Enter the marks of second subject: 95
Enter the marks of third subject: 99
Enter the marks of fourth subject: 93
Enter the marks of fifth subject: 100
Grade: A
6. Python program to print all numbers in a range divisible by a given number.
lower=int(input("Enter lower range limit:"))
upper=int(input("Enter upper range limit:"))
n=int(input("Enter the number to be divided by:"))
for i in range(lower,upper+1):
if(i%n==0):
print(i)
Output:
Enter lower range limit:1

96
Problem Solving and Python Programming 2020

Enter upper range limit:50


Enter the number to be divided by:5
5
10
15
20
25
30
35
40
45
50
7. Python program to read two numbers and print their quotient and remainder.
a=int(input("Enter the first number: "))
b=int(input("Enter the second number: "))
quotient=a//b
remainder=a%b
print("Quotient is:",quotient)
print("Remainder is:",remainder)
Output:
Enter the first number: 15
Enter the second number: 7
Quotient is: 2
Remainder is: 1
8. Python program to print odd numbers within a given range.
lower=int(input("Enter the lower limit for the range:"))
upper=int(input("Enter the upper limit for the range:"))
for i in range(lower,upper+1):
if(i%2!=0):
print(i)

97
Problem Solving and Python Programming 2020

Output:
Enter the lower limit for the range:1
Enter the upper limit for the range:16
1
3
5
7
9
11
13
15
9. Python program to find the sum of digits in a number.
n=int(input("Enter the number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits is:",tot)
Output:
Enter the number:1892
The total sum of digits is: 20
10. Python program to count the number of digits in a number
n=int(input("Enter the number:"))
count=0
while(n>0):
count=count+1
n=n//10
print("The number of digits in the number are:",count)

98
Problem Solving and Python Programming 2020

Output:
Enter the number:123
The number of digits in the number are: 3
11. Python program to check if a number is a palindrome.
n=int(input("Enter the number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is palindrome")
else:
print("The number is not a palindrome")
Output:
Enter the number:121
The number is palindrome
12. Python program to take the temperature in Celsius and convert it to Fahrenheit.
Celsius=int(input("Enter the Temperature in Celsius:"))
f=(Celsius*1.8)+32
print("Temperature in Fahrenheit is:",f)
Output:
Enter the Temperature in Celsius:32
Temperature in Fahrenheit is: 89.6
13. Python program to print squares of numbers.
for i in range(1,5,1):
print(i*i)
Output:
1 4 9 16

99
Problem Solving and Python Programming 2020

14. Python program to print cubes of numbers.


for i in range(1,5,1):
print(i*i*i)
Output:
1 8 27 64
15. Python program to print n odd numbers.
for i in range(1,10,2):
print(i)
Output:
13579
16. Python program to print n even numbers.
for i in range(2,10,2):
print(i)
Output:
2468
17. Python program to calculate simple interest.
p=int(input(“Enter principal amount:”))
n=int(input(“Enter number of years:”))
r=int(input(“Enter the rate of interest:”))
si=p*n*r/100
print(“Simple Interest is:”,si)
Output:
Enter principal amount:5000
Enter number of years:4
Enter the rate of interest:6
Simple Interest is:1200.0

100
Problem Solving and Python Programming 2020

CHAPTER 3

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.

101
Problem Solving and Python Programming 2020

102
Problem Solving and Python Programming 2020

CONTROL FLOW, FUNCTIONS

3.1 CONDITIONALS
3.1.1 Boolean values and operators
Boolean values:
Boolean data types have two values. They are 0 and 1.
→0 represents False
→1 represents True
True and False are keywords. Boolean values are used in comparisons and conditional
expressions. The most common way to produce boolean value is relational operators.

Operator Description Example


Equal to >>>4 = = 4
==
True
Not equal to >>> 4 != 3
!=
True
Greater than >>> 4 > 2
>
True
Less than >>> 4< 2
<
False
Greater than or equal to >>>4 >= 5
>=
False
Less than or equal to >>> 4<= 5
<=
True
3.1.2 Operators
Operators are the constructs which can manipulate the value of operands. Consider the
expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
Types of operators:
i) Arithmetic operators
ii) Comparison (Relational) operators
iii) Assignment operators

103
Problem Solving and Python Programming 2020

iv) Logical operators


v) Bitwise operators
vi) Membership operators
vii) Identity operators
i) Arithmetic operators
They are used to perform mathematical operations like addition, subtraction, multiplication etc.

Operator Name of operator

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus-Divides left hand operand by right hand operand and


returns remainder
** Power-Performs exponential (power) calculation on operators

Floor Division - The division of operands where the result is


the quotient in which the digits after the decimal point are
//
removed

Example Program:
x=5
y=5
print(“x+y=”,x+y)
print(“x-y=”,x-y)
print(“x*y=”,x*y)

104
Problem Solving and Python Programming 2020

print(“x/y=”,x/y)
print(“x%y=”,x%y)
print(“x//y=”,x//y)
Output:
x+y=30
x-y=20
x*y=125
x/y=5.0
x%y=0
x//y=5
ii) Comparison (Relational) operators
Comparison operators are used to compare values. It either returns True or False according
to the condition.

Operator Name of operator

== Equality
!= Not equal to
> Greater than
< Less than.
>= Greater than or equal to
<= Less than or equal to

Example Program:
x=10
y=20
print(“x>y=”,x>y)
print(“x<y=”,x<y)
print(“x==y=”,x==y)
print(“x!=y=”,x!=y)
105
Problem Solving and Python Programming 2020

print(“x>=y=”,x>=y)
print(“x<=y=”,x<=y)
Output:
x>y=False
x<y=True
x==y=False
x!=y=True
x>=y=False
x<=y=true
iii) Assignment operators
Assignment operators are used in Python to assign values to variables.

Operator Description

= Assigns values from right side operands to left side


operand
+= It adds right operand to the left operand and assign the
result to left operand
-= It subtracts right operand from the left operand and assign
the result to left operand
*= It multiplies right operand with the left operand and assign
the result to left operand
/= It divides left operand with the right operand and assign the
result to left operand
Example Program:
x=6
x+=5
print(“x+=”,x)
Output:
x+=11

106
Problem Solving and Python Programming 2020

iv) Logical operators


An expression containing logical operator returns either 0 or 1 depending upon whether
expression results true or false. Logical operators are and, or, not operators.

Operator Description Example


and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false not x

Example Program:
x=True
y=False
print(“x and y=”,x and y)
print(“x or y=”,x or y)
print(“not x=”,not x)
Output:
x and y=False
x or y=True
not x=False
v)Bitwise operators

Bitwise operators are used to perform bit-level operations which makes processing faster.

Operator Name of operator


& Bitwise AND
| Bitwise OR
~ Bitwise NOT
^ Bitwise XOR
>> Bitwise right shift

107
Problem Solving and Python Programming 2020

<< Bitwise left shift

Example Program:
x=2
y=3
print(“x&y=”,x&y)
Output:
x&y=2
vi) Membership operators
→It evaluates to find a value or a variable is in the specified sequence of string, list, tuple,
and dictionary or not.
→To check particular element is available in the list or not.
→The membership operators are in and not in.

Operator Description
in True if value/variable is found in the sequence
not in True if value/variable is not found in the sequence

Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
vii) Identity operators
They are used to check if two values (or variables) are located on the same part of the
memory.

Operator Description
is True if the operands are identical(refer to the same object)

108
Problem Solving and Python Programming 2020

is not True if the operands are not identical(do not refer to the same
object)
Example:
x=5
y=5
a = 'Hello'
b = 'Hello'
print(x is not y)
print(a is b)
Output:
False
True
3.1.3 Conditional Statements
i)Conditional if
If conditional is a decision making statement. It is always used with condition. It executes
code only if condition is satisfied.
syntax:
if condition:
statements
Flowchart:

False

condition

True

statements

109
Problem Solving and Python Programming 2020

Example Program: To provide bonus mark if the category is sports.


a=input(“enter the number1”)
b=input(“enter the number2”)
if(a>b):
print(“Biggest number is:”,a)
Output:
enter the number1
85
enter the number2
80
Biggest number is:80
ii) Alternative (if-else)
In the alternative the condition must be true or false. If the condition is true statements
inside the if get executed otherwise else part gets executed. The alternatives are called branches,
because they are branches in the flow of execution.
Syntax:
if (condition):
True statements
else:
False statements
Flowchart:

True False
if
condition

True statements False statements

110
Problem Solving and Python Programming 2020

Example Program 1: Odd or even number


n=int(input("Enter a number:"))
if(n%2==0):
print("Even number")
else:
print("Odd number")
Output:
Enter a number :4
Even number
Example Program 2: Positive or Negative number
n=int(input("Enter a number:"))
if(n>0):
print("Positive number")
else:
print("Negative number")
Output:
Enter a number 4
Positive number
iii) Chained conditionals (if-elif-else)
The elif is short for else if. This is used to check more than one condition. If the
condition1 is False, it checks the condition2 of the elif block. If all the conditions are False, then
the else part is executed.
Syntax:
if(condition1):
statement1
elif(condition2):
statement2
elif(condition3):
statement3
else:

111
Problem Solving and Python Programming 2020

default statements

Flowchart:

False
Condition

True
True
False
Statement 1 Condition

True False
Statement 2 Condition

3
True

Statement 3 Default statement

Example Program: Roots of quadratic equation


a=int(input("enter a value:"))
b=int(input("enter b value:"))
c=int(input("enter c value:"))

112
Problem Solving and Python Programming 2020

d=(b*b-4*a*c)
if(d==0):
print("same and real roots")
elif(d>0):
print("different real roots")
else:
print("imaginary roots")
Output:
enter a value:1
enter b value:0
enter c value:0
same and real roots
3.2 ITERATION/CONTROL STATEMENTS/LOOPING STATEMENTS
Iteration means repetition of loop until base condition is false. Repeated execution of set of
statements is called as iteration.
→state
→while
→for
→break
→continue
→pass
3.2.1 State
It is possible to have more than one assignment for the same variable. Reassignment
replaces existing value with new value.
Example Program1:
>>>x=10
>>>y=17
>>>print x
10
>>>x=18

113
Problem Solving and Python Programming 2020

>>>print x
18
Example Program2:
>>>x=10
>>>y=176
>>>x=8
>>>print x
8
3.2.2 While loop
While loop statement in Python is used to repeatedly executes set of statement as long as
a given condition is true. In while loop, test expression is checked first. The body of the loop is
entered only if the test expression is True.
Syntax:
while(condition):
body of while statements
Flowchart:

False
Condition

True
Body of while
statements

exit from loop

114
Problem Solving and Python Programming 2020

Example Program: Factorial of a numbers

n=input("enter the number”)


i=1
fact=1
while(i<=n):
fact=fact*i
i=i+1
print(“Factorial is”,fact)
Output:
enter the number
5
Factorial is 120
3.2.3 For loop
for in range:
We can generate a sequence of numbers using range () function. In range function have to
define the start, stop and step size as range(start, stop, step size).step size defaults to 1 if not
provided.
Syntax:
for loopvariable in range(start,step,stepsize)
Example Program: Factorial of a numbers

n=input("enter the number”)


fact=1
for i in range(1,n):
fact=fact*i
print(“Factorial is”,fact)
Output:
enter the number
5

115
Problem Solving and Python Programming 2020

Factorial is 125
for in sequence:
The for loop in Python is used to iterate over a sequence (list, tuple, string).. Loop
continues until we reach the last element in the sequence.
Syntax:
for loopvariable in sequence:
Body of for statements

Flowchart:

False
Condition

Body of for
statements

Exit from loop


Sequence can be a list, strings or tuples:

Sl.No Sequences Example Output

R
for i in "Ramu": A
1. For loop in string
print(i) M
U
for i in [2,3,5,6,9]: 2
2. For loop in list
print(i) 3

116
Problem Solving and Python Programming 2020

5
6
9
2
for i in (2,3,1):
3. For loop in tuple 3
print(i)
1

3.2.4 Break
Break statements can alter the flow of a loop. It terminates the current loop and executes
the remaining statement outside the loop.
Syntax:
i) while loop
while(condition):
if(condition):
break
ii) for loop
for loop variable in sequence:
if(condition):
break
Flowchart:

condition
False
True

Break?

Body of loop

117
Problem Solving and Python Programming 2020

Example Program:

for i in "welcome":
if(i=="c"):
break
print(i)

Output:
w
e
l
3.2.5 Continue

It terminates the current iteration and transfer the control to the next iteration in the loop.
Syntax:
i) while loop
while(condition):
if(condition):
continue
ii) for loop
for loopvariable in sequence:
if(condition):
continue
Flowchart:

condition

Continue

Body of loop
118
Problem Solving and Python Programming 2020

Example Program:

for i in "welcome":
if(i=="c"):
continue
print(i)
Output:
w
e
l
o
m
e
3.2.6 Pass
It is a null statement, nothing happens when it is executed.

Syntax:

pass

Example Program:

for i in “welcome”:

if (i == “c”):

pass

print(i)

Output:

w
e
l
c
o
119
Problem Solving and Python Programming 2020

m
e

3.2.7 Difference between break and continue

Sl.No break continue

1 It terminates the current loop and It terminates the current iteration and
executes the remaining statement outside transfer the control to the next iteration in
the loop. the loop.
2 syntax: syntax:
break continue
3 for i in "welcome": for i in "welcome":
if(i=="c"): if(i=="c"):
break continue
print(i) print(i)
4 w w
e e
l l
o
m
e

3.3 FRUITFUL FUNCTION


A function that returns a value is called fruitful function.
Example program:
def add():
a=10
b=20
c=a+b
return c
c=add()
120
Problem Solving and Python Programming 2020

Void function:
A function that does not return any value is called void function.
Example 1:
print(“Hello”)
Example 2:
def add():
a=10
b=20
c=a+b
print(c)
add()
3.3.1 Return values
Return statement may or may not send back any value to main program. The return
statement is also used to exit a function and go back to place where it was called, return
keywords are used to return the values from the function.
Syntax:
return(expression)

Fruitful function Return the value


Input
Example:
return a – return 1 variable
return a,b– return 2 variables
return a,b,c– return 3 variables
return a+b– return expression
return 8– return value
3.3.2 Parameters / Arguments
Parameters are the variables which used in the function definition. Parameters are inputs
to functions. Parameter receives the input from the function call. It is possible to define more than
one parameter in the function definition.

121
Problem Solving and Python Programming 2020

Types of parameters/arguments:
i) Required/positional parameters
ii) Keyword parameters
iii) Default parameters
iv) Variable length parameters

i) Required/ positional parameter


The number of parameter in the function definition should match exactly with number of
arguments in the function call.
Example Output

def student( name, roll ):


print(name,roll) Ajitha 98
student(“Ajitha”,98)

ii) Keyword parameter


When we call a function with some values, these values get assigned to the parameter
according to their position. When we call functions in keyword parameter, the order of the
arguments can be changed.
Example Output
def student(name,roll,mark):
print(name,roll,mark) Mala 90 100
student("Mala",90,100)

iii) Default parameter


Python allows function parameter to have default values; if the function is called without
the argument, the argument gets its default value in function definition
Example Output
def student( name, age=20):
print (name, age) Latha 20
student( “Latha”): Aarika 20
122
Problem Solving and Python Programming 2020

student( “Aarika”):

iv) Variable length parameter


Sometimes, we do not know in advance the number of arguments that will be passed into
a function. Python allows us to handle this kind of situation through function calls with number
of arguments. In the function definition we use an asterisk (*) before the parameter name to
denote this is variable length of parameter.
Example Output
def student( name,*mark):
print(name, mark) Vikash (102 ,90)
student (“Vikash”,102,90)

3.3.3 Global and Local scope


Global scope:
The scope of a variable refers to the places that you can see or access a variable. A
variable with global scope can be used anywhere in the program. It can be created by defining a
variable outside the function.
Example Output

a=50
def add():
b=20
c=a+b Global variable

print(c) 70
def sub():
b=30
Local variable
c=a-b
print(c) 20

123
Problem Solving and Python Programming 2020

print(a) 50

3.3.4 Function composition


Function composition is the ability to call one function from within another function. It is
a way of combining functions such that the result of each function is passed as the argument of
the next function. -9/-
Example Program: Find sum and average using function composition
def sum(a,b):
sum=a+b
return sum
def avg(sum):
avg=sum/2
return avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
sum=sum(a,b)
avg=avg(sum)
print("the avg is",avg)
Output:
enter a:4
enter b:8
the avg is 6.0
3.3.5 Recursion
Recursion is a programming technique that has a recursive function that calls itself again
and again until the condition is reached.
Example Program: Factorial of a given number using recursion
def fact(n):
if(n==1):
return 1

124
Problem Solving and Python Programming 2020

else:
return n*fact(n-1)
n=int(input("enter no. to find fact:"))
fact=fact(n)
print("Fact is",fact)
Output:
enter no. to find fact:5
Fact is 120
3.4 STRINGS
String is defined as sequence of characters represented in quotation marks (either
single quotes ( ‘ ) or double quotes ( “ ). An individual character in a string is accessed using a
index. The index should always be an integer (positive or negative). A index starts from 0 to
n-1. Strings are immutable i.e. the contents of the string cannot be changed after it is created.
String operators/operations:
i) Indexing
ii) Slicing
iii) Concatenation
iv) Repetition
v) Membership
vi)Comparision

i) Indexing

Positive indexing helps in accessing the string from the beginning. Negative subscript helps
in accessing the string from the end.

>>>a=”HELLO HAI”
>>>print(a[0])
>>>H
>>>print(a[-1])
>>>I
ii) Slicing

125
Problem Solving and Python Programming 2020

The slice[start : stop] operator extracts sub string from the strings. A segment of a string
is called a slice.
print a[0:4] – HELL
print a[ :3] – HEL
print a[0: ]- HELLO
iii) Concatenation
The + operator joins the text on both sides of the operator.
a=”save”
b=”water”
>>>print(a+b)
savewater
iv) Repetition
The * operator repeats the string on the left hand side times the value on right hand side.
a=”python”
>>>print(3*a)
pythonpythonpython
v) Membership
Using membership operators to check a particular character is in string or not. Returns
true if present
>>> s="good morning"
>>>"m" in s
True
>>> "a" not in s
True
vi)Comparison
The strings can be compared using relational operators.
>>>msg1=”Good”
>>>msg2=”Good”
>>>msg1==msg2
True

126
Problem Solving and Python Programming 2020

3.4.1 String slices


A part of a string is called string slices. The process of extracting a sub string from a
string is called slicing. The Slice[n : m] operator extracts substring from the strings. A segment
of a string is called a slice.
a=”HELLO”
print a[0:4] – HELL
print a[ :3] – HEL
print a[0: ]- HELLO

3.4.2 Immutability
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.

Operations Example Output

element assignment a="PYTHON" TypeError: 'str' object does not


a[0]='x' support element assignment
New strings can be created a=”Python” PythonProgram
from the old c=a+”Program”
print c

3.4.3 String built in functions and methods (or) String Functions


A method is a function that “belongs to” an object.
Syntax :
To access the method
stringname.method()
Example:
a=”happy birthday”
here, a is the string name.

127
Problem Solving and Python Programming 2020

Sl.No Syntax Example Description


1 a. capitalize() >>> a. capitalize() capitalize only the first letter in
' Happy birthday’ a string
2 a. upper() >>> a. upper() change string to upper case
'HAPPY BIRTHDAY’
3 a. lower() >>> a. lower() change string to lower case
' happy birthday’
4 a.title() >>> a.title() change string to title case i.e.
' Happy Birthday ' first characters of all the words
are capitalized.

5 a.swapcase() >>>a.swapcase() change lowercase characters to


'HAPPY BIRTHDAY' uppercase and vice versa
6 a.split() >>> a.split() returns a list of words
['happy', 'birthday'] separated by space
7 a.count(substring) >>> a.count('happy') returns the number of
1 occurences of substring
8 a.replace(old,new) >>>a.replace('happy', replace all old substrings
'wishyou happy') with new substrings
'wishyou happy
birthday'

9 a.isupper() >>> a.isupper() checks whether all the case


False based characters (letters) of
the string are uppercase.
10 a.islower() >>> a.islower() checks whether all the
True casebased
characters (letters) of
the string are lowercase.

128
Problem Solving and Python Programming 2020

11 a.isalpha() >>> a.isalpha() checks whether the string


False consists of alphabetic
characters only.

12 a.isalnum() >>> a.isalnum() checks whether the string


False consists of alphanumeric
characters.
13 a.isdigit() >>> a.isdigit() checks whether the string
False consists of digits only.

14 a.isspace() >>> a.isspace() checks whether the string


False consists of whitespace only.
15 a.istitle() >>> a.istitle() checks whether string is title
False cased.
16 a.startswith(substrin >>> a.startswith("h") checks whether string starts
g) True with substring
17 a.endswith(substrin >>>a.endswith("y") checks whether the string ends
g) True with the substring
18 len(a) >>>len(a) Return the length of the string
>>>14
19 min(a) >>>min(a) Return the minimum
>>>’ ‘ character in the string
20 max(a) max(a) Return the maximum
>>>’y’ character in the string

3.4.4 String modules


→A module is a file containing Python definitions, functions, statements.
→Standard library of Python is extended as modules.
→To use these modules in a program, programmer needs to import the module.
→Once we import a module, we can reference or use to any of its functions or variables
129
Problem Solving and Python Programming 2020

in our code.
→There is large number of standard modules also available in python.
→Standard modules can be imported the same way as we import our user-defined
modules.
Syntax:
import module_name
Example Program:
import string
print(string.punctuation)
print(string.digits)
print(string.printable)
print(string.capwords("happy birthday"))
print(string.hexdigits)
print(string.octdigits)

Output:

!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
0123456789
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
/:;<=>?@[\]^_`{|}~
Happy Birthday
0123456789abcdefABCDEF
01234567

3.4.5 List as array


Array:
Array is a collection of similar elements. Elements in the array can be accessed by index.
Index starts with 0. Array can be handled in Python by module named array. To create array
have to import array module in the program.
Syntax:
130
Problem Solving and Python Programming 2020

import array
Syntax to create array:
arrayname = modulename.functionname(‘datatype’,[elements])
Example:
a=array.array(‘i’,[1,2,3,4])
Here,
a- array name
array- module name
i- integer datatype

Convert list into array:


fromlist() function is used to append list to array. Here the list is act like a array.
Syntax:
arrayname.fromlist(listname)
Example Program: Program to convert list into array
import array
sum=0
l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist(l)
for i in a:
sum=sum+i
print(sum)
Output
35
Methods in array:
a=[2,3,4,5]
Sl.No Syntax Example Description
1 array(data type,value list) array(‘i’,[2,3,4,5]) This function is used to create an
array with data type and value list

131
Problem Solving and Python Programming 2020

specified in its arguments.


2 append() >>>a.append(6) This method is used to add end of
[2,3,4,5,6] the array.
3 insert(index,element) >>>a.insert(2,10) This method is used to add the
[2,3,10,5,6] value at the position specified in
its argument.
4 pop(index) >>>a.pop(1) This function removes the
[2,10,5,6] element at the position
mentioned in its argument, and
returns it.
5 index(element) >>>a.index(2) This function returns the index of
0 value
6 reverse() >>>a.reverse() This function reverses the
[6,5,10,2] array.
7 count() a.count() This is used to count number of
4 elements in an array

3.5 ILLUSTRATIVE PROGRAMS


3.5.1 Square root using Newton’s method
def newtonsqrt(n):
root=n/2
for i in range(10):
root=(root+n/root)/2
print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)
Output:
enter number to find Sqrt: 9
3.0

132
Problem Solving and Python Programming 2020

3.5.2 GCD of two numbers


def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=input(“Enter number1:”)
b=input(“Enter number2:”)
g=gcd(a,b)
print(“gcd is”,g)
Output:
Enter a number1:8
Enter a number2:24
gcd is 8
3.5.3 Exponent of a number
def power(base,exp):
if(exp==1):
return(base)
else:
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value:"))
result=power(base,exp)
print("The exponent is:",result)
Output:
Enter base: 2
Enter exponential value:3
The exponent is: 8
3.5.4 Sum of array elements
a=[2,3,4,5,6,7,8]

133
Problem Solving and Python Programming 2020

sum=0
for i in a:
sum=sum+i
print("The total is",sum)

Output:
The total is 35
3.5.5 Linear search
mylist=[11,23,38,40,52,63,78,98,29,45]
print(mylist)
x = int(input("Enter number to search: "))
found=False
for i in range(len(mylist)):
if(mylist[i] == x):
found=True
print ("Element found at position:",i+1)
break
if(found==False):
print "Element not found"
Output:

[11, 23, 38, 40, 52, 63, 78, 98, 29, 45]
Enter number to search: 78
(‘Element found at position:’ 7)
[11, 23, 38, 40, 52, 63, 78, 98, 29, 45]
Enter number to search: 2
Element not found
3.5.6 .Binary search
def bsearch(list,x):
first = 0
last= len(list)-1
134
Problem Solving and Python Programming 2020

while (first<=last):
midpoint= (first+ last)//2
if x==list[midpoint]:
return midpoint
elif(x<list[midpoint]):
last=midpoint-1
else:
first= midpoint+1
return -1
list=[10,20,30,40,50]
print("Original list is:",list)
x=input("Enter the element to be searched:")
pos=bsearch(list,x)
if(pos!=-1):
print “Element found at the position:”,pos
else:
print “Element not found”
Output:
Original list is:[10,20,30,40,50]
Enter the element to be searched:30
Element found on position:2
Original list is:[10,20,30,40,50]
Enter the element to be searched:60
Element not found

135
Problem Solving and Python Programming 2020

PART- A (2 Marks with Answers)


1. Define Boolean expression with example.
A boolean expression is an expression that is either true or false. The values true and
false are called Boolean values.
Example:
>>> 5 == 6
False
True and False are special values that belongs to the type bool; they are not strings.
2. What are the different types of operators?

→Arithmetic Operator (+, -, *, /, %, **, // )


→Relational operator ( == , !=, < >, < , > , <=, >=)
→Assignment Operator ( =, += , *= , - =, /=, %= ,**= )
→Logical Operator (AND, OR, NOT)
→Membership Operator (in, not in)
→Bitwise Operator (& (and), | (or) , ^ (binary Xor), ~(binary 1’s complement) ,
<< (binary left shift), >> (binary right shift))
→Identity Operator(is, is not)
3. Explain modulus operator with example.
The modulus operator works on integers and yields the remainder when the first operand
is divided by the second. In Python, the modulus operator is a percent sign (%). The syntax is
same as for other operators:
Example:
>>> remainder = 7 % 3
>>> print remainder
1
So 7 divided by 3 is 2 with 1 left over.
4. Explain relational operators.
The == operator is one of the relational operators; the others are:
X! = y # x is not equal to y
x > y # x is greater than y
136
Problem Solving and Python Programming 2020

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
5. Explain Logical operators
There are three logical operators: and, or, and not. For example, x > 0 and x < 10 is true
only if x is greater than 0 and less than 10. n%2 == 0 or n%3 == 0 is true if either of the
conditions is true, that is, if the number is divisible by 2 or 3. Finally, the not operator negates a
Boolean expression, so not(x > y) is true if x > y is false, that is, if x is less than or equal to y.
Non-zero number is said to be true in Boolean expressions.
6. What is conditional execution?

The ability to check the condition and change the behavior of the program accordingly is
called conditional execution.
If statement:
The syntax of if statement is:
Syntax:
if
statement:
Example:
if x > 0:
print 'x is positive'
The boolean expression after ‘if’ is called the condition. If it is true, then the indented statement
gets executed. If not, nothing happens.

7. What is alternative execution?


A second form of if statement is alternative execution, that is, if …else, where there are two
possibilities and the condition determines which one to execute.
Example:
if x%2 == 0:
print 'x is even'
else:

137
Problem Solving and Python Programming 2020

print 'x is odd'


8. What are chained conditionals?
Sometimes there are more than two possibilities and we need more than two branches.
One way to express a computation like that is a chained conditional.
Example:
if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y'
else:
print 'x and y are equal'
9. Explain ‘for loop’ with example.
The general form of a for statement is
Syntax:
for loop variable in sequence:
Body of for statements
Example:
x=4
for i in range(0, x):
print i
10. What is a break statement?
When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
Example:
while True:
line = raw_input('>')
if line == 'done':
break
print line
print 'Done!'

138
Problem Solving and Python Programming 2020

11. What is a continue statement?


The continue statement works somewhat like a break statement. Instead of forcing
termination, it forces the next iteration of the loop to take place, skipping any code in between.
Example:
for num in range(2,10):
if num%2==0;
print “Found an even number”, num
continue
print “Found a number”, num
12. Compare return value and composition.
Return value:
Return gives back or replies to the caller of the function. The return statement causes our
function to exit and hand over back a value to its caller.
Example:
def area(radius):
temp = math.pi * radius**2
return temp
Composition:
Calling one function from another is called composition.
Example:
def circle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
13. What is recursion?
The process in which a function calls itself directly or indirectly is called recursion and
the corresponding function is called as recursive function.

Example:
def factorial(n):
if n == 1:
139
Problem Solving and Python Programming 2020

return 1
else:
return n * factorial(n-1)
14. Explain global and local scope.
The scope of a variable refers to the places that we can see or access a variable. If we
define a variable on the top of the script or module, the variable is called global variable. The
variables that are defined inside a class or function is called local variable.
Example:
def my_local():
a=10
print(“This is local variable”)
Example:
a=10
def my_global():
print(“This is global variable”)
15. Compare string and string slices.
A string is a sequence of character.
Example:
fruit = ‘banana’
String slices:
A segment of a string is called string slice, selecting a slice is similar to selecting a
character.
Example:
>>> s =' Pythonprogram'
>>> print s[0:5]
pytho
>>> print s[6:12]
progra

140
Problem Solving and Python Programming 2020

16. Define string immutability.


Python strings are immutable. ‘a’ is not a string. It is a variable with string value. We
can’t mutate the string but can change what value of the variable to a new string.

Example:
a = “foo”
b=a
a=a+a
print a
print b

Output:
foofoo
foo
It is observed that ‘b’ hasn’t changed even though ‘a’ has changed.
17. Mention a few string functions.
s.captilize() – Capitalizes first character of string
s.count(sub) – Count number of occurrences of sub in string
s.lower() – converts a string to lower case
s.split() – returns a list of words in string
18. What are string methods?
A method is similar to a function—it takes arguments and returns a value—but the syntax
is different. For example, the method upper takes a string and returns a new string with all
uppercase letters. Instead of the function syntax upper(word), it uses the method syntax
word.upper()
>>> word = 'lion'
>>> new_word = word.upper()
>>> print new_word
LION

141
Problem Solving and Python Programming 2020

19. Explain about string module.


The string module contains number of useful constants and classes, as well as some
deprecated legacy functions that are also available as methods on strings.
20. What is the purpose of pass statement?
Using a pass statement is an explicit way of telling the interpreter to do nothing.
Example:
def bar():
pass
If the function bar() is called, it does absolutely nothing
21 .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.
22 .Explain string comparison with an example.
The comparison operator works on string to check if two strings are equal.
>>>word=‘python program‘
>>>if word==‘pythonprogram‘
print( ‘Both are Equal‘)
Output:
Both are Equal
23. How to split strings and what function is used to perform that operation?
The str.split() method is used to split strings up.
Example:
>>>book=‘Problem Solving and Python Programming‘

>>>print(book.split()) [‗Problem‘, ‗Solving‘, ‗and‘, ‗Python‘, ‗Programing‘]


24. 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
142
Problem Solving and Python Programming 2020

25. Write a program to accept two number,multiply them and print the result.
(JANUARY 2018)
print(“Enter two numbers:”)
val1=int(input())
val2=int(input())
prod=val1*val2
print(“product is:”,prod,”\n”)
26. Write a python program to accept two numbers, find the greatest and print the result.
(JANUARY 2018)
print(“Enter two numbers:”)
num1=input()
num2=input()
number1=int(num1)
number2=int(num2)
if number1>number2:
Largest=number1
else:
Largest=number2
print(“largest number is:”,largest)
27. Present the flow of execution for a while statement. (JANUARY 2019)
While loop statement in Python is used to repeatedly executes set of statement as long as
a given condition is true. In while loop, test expression is checked first. The body of the loop is
entered only if the test expression is True.
Syntax:
while(condition):
body of while statements
28. Define recursion with example. (JANUARY 2019)
Recursion is a programming technique that has a recursive function that calls itself again
and again until the condition is reached.

143
Problem Solving and Python Programming 2020

29. Do loop statements have else clause? When will it be executed? (JANUARY 2020)

Yes. Loop’s else part runs if no break occurs and the condition is false

30. Write a program to display a set of strings using range () function. (JANUARY 2020)

st=" hai welcome to cse" x=' '


for s in range(len(st)):
x=x+st[s]
print(x)

144
Problem Solving and Python Programming 2020

PART-B (Possible Questions)


1. Explain the syntax and flow chart of the following loop statements
a. for loop
b. while loop
2. Explain recursive function. How do recursive function works? Explain with a help of program
3. Create a program to reverse a string without using recursion
4. Illustrate the concept of local and global variables
5. Discuss the methods to manipulate the arrays in python
6. Create a python program to find the given year is leap or not
7. Investigate on mutability and immutability in python
8. Illustrate the flow chart and syntax of if-elif-else statements
9. Explain the types of function arguments in python
10. Explain break and continue statement with the help of for loop in an example.
11. Write a program for binary search using Arrays
12. Define methods in a string with an example program using at least five methods.
13. What is the use of pass statement, illustrate with an example.
14. How to access characters of a string?
15.i.Appraise with an example nested if and elif header in python (JANUARY 2018)
ii.Explain with an example while loop,break statement and continue statement in python
16.i.Write a python program to find the factorial of a given number without recursion and with
Recursion. (JANUARY 2018)
ii.Write a python program to generate first ‘N’ fibonacci numbers.
17. a) List the three types of conditional statements and explain them (16)
b) i)Python strings are immutable, Justify with an example (8)
ii)Write a python code to perform binary search. Trace it with an example of your choice.
(8) (JANUARY 2019)
18.i)If you are given three sticks, you may or may not be able to arrange them in a triangle. For
example, if one of the sticks is 12 inches long and the other two are one inch long, you will not
be able to get the short sticks to meet in the middle. For any three length, there is a simple test to

145
Problem Solving and Python Programming 2020

see if it is possible to form a triangle: If any of three lengths is greater than the sum of the other
two, then you cannot form a triangle. Otherwise ,you can.
i)Write a function named is – triangle that takes three integers as arguments, and that prints
either “yes” or “no”, depending on whether you can or cannot form a triangle from sticks with
the given lengths. (4)
ii)Write a function that prompts the user to input three stick lengths, converts them to
integers, and uses is – triangle to check whether sticks with the given lengths can form a triangle
(4).
iii)Write a python program to generate all permutations of a given string using built-in
functions. (8) (JANUARY 2020)
19.i)Compare list and array with example.Can list be considered as an array?justify (6)
ii)Write a python function are Anagram1() to check whether two strings are anagram of each
other or not using built-in functionand are Anagram2() to check the anagram without using built-
in function. (10) (JANUARY 2020)

146
Problem Solving and Python Programming 2020

PART C (Possible Questions)

1. Write a python program to design simple calculator performing arithmetic functions like
addition, subtraction, multiplication and division with the input given by user.
2. Create a program for linear search using Arrays
3. Illustrate a program to find GCD of m and n.
4. How to find the square root of a number using newton’s method
5. Write a python program to sum an array of numbers
6. Write a python program for student mark system.
7. Write a python program greatest of three numbers.

147
Problem Solving and Python Programming 2020

Additional Programs
1. Positive or negative number
n=eval(input("enter a number:"))
if(n>=0):
print("positive number")
else:
print("negative number")
Output:
enter a number:88
positive number
2. Leap year or not
y=eval(input("enter a yaer:"))
if(y%4==0):
print("leap year")
else:
print("not leap year")
Output:
enter a year:2004
leap year
3. Greatest of three numbers
a=eval(input(“enter the value of a:”))
b=eval(input(“enter the value of b:”))
c=eval(input(“enter the value of c:”))
if(a>b):
if(a>c):
print(“The greatest number is”,a)
else:
print(“The greatest number is”,c)
else:
if(b>c):

148
Problem Solving and Python Programming 2020

print(“The greatest number is”,b)


else:
print(“The greatest number is”,c)
Output
enter the value of a: 9
enter the value of b: 1
enter the value of c: 8
The greatest number is 9
4. Student mark system
mark=eval(input("enter your mark:"))
if(mark>=90):
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
Output:
enter your mark:78
grade:B
5. Sum of n numbers
n=eval(input("Enter the value of n:"))
i=1
sum=0
while(i<=n):
sum=sum+i
i=i+1

149
Problem Solving and Python Programming 2020

print(sum)
output
Enter the value of n :
10
55
6. Print no’s divisible by 5 not by 10
n=eval(input("enter a"))
for i in range(1,n,1):
if(i%5==0 and i%10!=0):
print(i)
Output:
enter a:30
5
15
25

150
Problem Solving and Python Programming 2020

CHAPTER 4

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.

151
Problem Solving and Python Programming 2020

152
Problem Solving and Python Programming 2020

LISTS, TUPLES, DICTIONARIES

4.1 LIST
List contain elements of various data types, the list is enclosed by square brackets where
elements are separated by commas. The values in a list are called elements or items. A list within
another list is called nested list.
→ List values can be accessed using slice operator ([] or [:])
→ list[0] represents beginning of list
→ list[-1] represents ending of list
Syntax:
listname=[value1,value2,…value n]
Example :
>>>mylist = [10,10.5, ‘programming’]
Example program for creating lists:
list1 = [‘Rama’, ‘Delhi’, 2018]
list2 = [10, 20, 30, 40, 50]
list3 = []
list4 = [‘Prema’, 2018, 99.8, [‘Mumbai’, ‘India’]]
print list1
print list2, list3
print list4
Output:
[‘Rama’, ‘Delhi’, 2018]
[10, 20, 30, 40, 50] [ ]
[‘Prema’, 2018, 99.8, [‘Mumbai’, ‘India’]]
Creating list:
i) The simplest way to create a list is enclose the elements in square brackets([])
nlist =[10,20,30,40]
slist =[“Hai”, “Python”]
ii) A list that contains no element is called an empty list. It can be created with empty brackets [].
elist = []
153
Problem Solving and Python Programming 2020

iii) A list within another list is called a nested list.


nlist =[“phyton”,2.5,[50,100,10,55]]
Accessing list elements:
The indices of list’s elements are numbered from 0 from the left end and numbered from
-1 from the right end. 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.
Indexing:
Just like strings, we can access elements on a list with the index. The various types are
i) Negative indexing
The index of -1 refers to the last item, -2 to the second to the last item and so on.
Example Program:
>>>birds[“parrot”,”Dove”,”duck”,”cuckoo”]
>>>birds[-1]
cuckoo
>>> birds[-4]
parrot
ii) Nested indexing:
A list within another list is called as nested list.
Example Program:
>>>nlist = [“Python”,8.5,[5,1,3,4,5.5]]
>>>nlist[0]
Python
>>>nlist[0][3]
h
4.1.1 List operations(List operators)
List provides a set of operations. They are
i) Concatenation
ii) Repetition
iii) Indexing

154
Problem Solving and Python Programming 2020

iv) Membership
i) Concatenation
The list can be concatenated by using ‘+’ operator.
Example:
>>>a = [1,2,3]
>>>b =[4,5,6]
>>>c =a+b
>>>c
[1,2,3,4,5,6]
ii) Repetition
The list can be repeated by using * operator.
Example:
>>>a =[1,2,3]
>>>a*2
[1,2,3, 1,2,3]
>>>[1]*5
[1,1,1,1,1]
iii) Indexing
The list elements can be accessed by using index operator ([]).
Example:
>>>a =[1,2,3]
>>>a[0]
1
>>>a[1]
2
>>>a[2]
3
>>>a[-1]
3

155
Problem Solving and Python Programming 2020

iv) Membership
There are 2 membership operators in python programming.
i) in - Returns true if value is in list, returns false if value is not in list.
ii) not in - Returns true if value is not in list, returns false if value is in list.
Example:
>>>a= [1,2,3]
>>>1 in a
True
>>>4 in a
False
>>>3 not in a
False
4.1.2 List slices
A segment of list is called as list slice. The list elements can be accessed using the slice
operator ([]). Slice operator [n:m] returns a part of list from nth element to mth element ,
including first and excluding last.
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 equal
to the second, the slice is an empty string. If both indices are omitted, the slice is a given string
itself.
Syntax:
listname [start: finish -1]
Example:
>>>mylist=[‘Python’,10,10.5,’program’]
>>>mylist[0]
‘Python’
>>>mylist[1]
10
>>>mylist[2]
10.5

156
Problem Solving and Python Programming 2020

>>>mylist[3]
‘program’
>>>mylist[0:3]
[‘Python’,10,10.5]
>>>mylist[1:3]
[10, 10.5]
>>>mylist[:3]
[‘Python’,10,10.5]
>>>mylist[:]
[‘Python’,10,10.5,’program’]
>>>mylist[1:]
[10,10.5,’program’]
mylist
python 10 10.5 program
0 1 2 3
mylist[0] -> element in 0th position.
mylist[-1] -> element in ending of list
mylist[0:3] -> Starting from 0th position to 2nd position
mylist[1:] -> ending position is not given , so 1st position to ending of list
mylist[:] -> beginning to ending of list.
4.1.3 List methods
Python provides a set of list methods. They are
i) append()
ii) extend()
iii) sort()
iv) reverse()
v) pop()
vi) clear()
vii) index()
viii) count()

157
Problem Solving and Python Programming 2020

ix) insert()
x) remove()
xi) copy()
i) append()
Adds element to the end of specified list and does not return any value.
>>>a =[1,2,3]
>>>a.append(4)
>>>a
[1,2,3,4]
ii) extend()
This method add all elements of list to another list.
>>>a= [1,2,3]
>>>b=[4,5,6]
>>>a.extend(b)
>>>a
[1,2,3,4,5,6]
iii) sort()
This method sorts elements in list.
>>>a= [3,1,2]
>>>a.sort()
>>>a
[1,2,3]
iv) reverse()
This method reverse the elements in a list.
>>>a =[1,2,3]
>>>a.reverse()
>>>a
[3,2,1]

158
Problem Solving and Python Programming 2020

v) pop()
This method removes and returns an element at the given index. If the index is not given,
it removes and returns the last element on the list.
Example:
list=[“eng”,”chem”,”python”,”maths”]
>>>list.pop(2)
python
>>>list
[“eng”,”chem”,”maths”]
>>>list.pop()
[“eng”,”chem,’python”]
vi) clear()
This method clear elements in a list.
>>>a= [1,2,3]
>>>a.clear()
>>>print(a)
[]
vii) index()
This method returns index of given element. If the element is not in the list it returns
error.
>>>a= [1,2,3]
>>>a.index(2)
1
viii) count()
It counts how many times the elements occur in the list.
>>>a= [1,2,3,2,2,1,3]
>>>a.count(3)
2
Syntax:
listname.count(value)

159
Problem Solving and Python Programming 2020

ix) insert()
It inserts an element on a desired position of a list.
Syntax:
listname.insert(index,element)
>>>a=[1,2,3]
>>>a.insert(1,4)
>>>a
[1,4,2,3]
x) remove()
It removes the specified element from the list.
>>>a=[1,2,3]
>>>a.remove(2)
>>>print(a)
[1,3]
xi) copy()
It copies one list to another list.
>>>a =[1,2,3]
>>>b=a.copy()
>>>b
[1,2,3]
Syntax:
listname.copy()
List functions:
i) len()
ii) max()
iii) min()
iv) cmp()
v) sum()
vi) sorted()
i) len() : Returns the number of elements in a list.

160
Problem Solving and Python Programming 2020

>>>a= [1,2,3,4]
>>>len(a)
4
ii) max(): Returns maximum value from the list .
>>>a= [1,2,3,4]
>>>max(a)
4
iii) min(): Returns minimum value from list.
>>>a= [1,2,3,4]
>>>min(a)
1
iv) cmp(): Compares the elements of lists.
>>>list1 = [123, 'xyz']
>>>list2 = [456, 'abc']
>>>print cmp(list1, list2)
-1
>>>print cmp(list2, list1)
1
>>>list3 = list2 + [786];
>>>print cmp(list2, list3)
-1
v) sum(): It returns the sum of all elements in a list.
>>>a= [5,10,15,5,4]
>>>sum(a)
39
vi) sorted(): Returns the sorted list of elements in ascending order.
>>>a= [4,3,2,1]
>>>sorted(a)
[1,2,3,4]

161
Problem Solving and Python Programming 2020

4.1.4 List loop [Traversing a loop]


The most common way to traverse elements of a list is using for loop. The looping in a
list is done by for loop. There are two types of for looping
i) for-sequence (for-in-loop)
ii) for-range()
i) for-sequence
for loop is used to read elements of list.
Example:
>>>for i in [2,3,5,6,9]
print (i)
Output:
2
3
5
6
9
ii) for-range
To update elements of list, we need to specify the range.
Example Program1:
>>>for i in range(0,4):
data[i]=[0]*3
>>>data
[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]
4.1.5 List mutability
The list is a mutable data structure, that means 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. Also
mutability is the ability of data to be changed without entirely recreating it.
Example:
>>>for i in range(0,4)

162
Problem Solving and Python Programming 2020

data[i]=[0]*3
>>>data
[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]
>>>data[1][1]
0
>>>data[2][2]
0
>>>data[1][1]
8
>>>data[2][2]
7
>>>data[1][1]
8
>>>data[2][2]
7
>>>data
[0,0,0],[0,8,0],[0,0,0],[0,0,0],[0,0,0]
4.1.6 List aliasing
List aliasing is defined as circumstance where two (or) more variables refer to the same object.
Example:
>>>a=[1,2,3]
>>>b=a
>>>b is a
True
>>>b is not a
False
In this example, a is assigned to b then both variables refers to same objects.
a
[1,2,3]
b

163
Problem Solving and Python Programming 2020

Here, the same list has two different names (‘a’ and ‘b’).so it is aliased.
If the aliased object is mutable, modifications done in one object affect the other object also.
Aliasing with mutable object:
Lists are mutable (changeable)
Example:
>>>a=[1,2,3]
` >>>b=a
>>>a
[1,2,3]
>>>b
[1,2,3]
>>>a[0]=10
>>>a
[10,2,3]
>>>b
[10,2,3]
4.1.7 Cloning list
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. This can be done using
i) list() function
ii) copy() function
iii) copy.deepcopy() function

i) list() function
built-in list() function can be used for cloning lists with the following syntax
Syntax:
newlistname= list(oldlistname)

164
Problem Solving and Python Programming 2020

Example:
>>>a= [1,2,3]
>>>b= list(a)
>>>a
[1,2,3]
>>>b
[1,2,3]
>>>a[0]=4
>>>a
[4,2,3]
>>>b
[1,2,3]
ii) copy() function
copy.copy() is little slower than list() since it has to determine data type of old list first.
Syntax:
newlistname= copy.copy(oldlistname)
Example:
>>>import copy
>>>a= [1,2,3]
>>>b= copy.copy(a)
>>>a
[1,2,3]
>>>b
[1,2,3]
iii) copy.deepcopy() function
copy.deepcopy() is the slowest and memory-consuming method.
Syntax :
newlistname = copy.deepcopy(Oldlistname)
Example Program1:
import copy

165
Problem Solving and Python Programming 2020

oldlist = [10, 20, 30, 40, 70]


newlist = copy.deepcopy(oldlist) # Returns a deep copy of oldlist
print(oldlist)
print(newlist)
Output:
[10, 20, 30, 40, 70]
[10, 20, 30, 40, 70]
4.1.9 List parameters
A list can be passed as a parameter to a function. This parameter is passed by reference.
Changes made in list inside function will affect list even after returning function.
Example Program1: To circulate values of n variable .
def circulate(1,n):
newlist= l[[n:]+ l[n:]
return newlist
list= [1,2,3,4,5]
program(“original list:”, list)
mylist= circulate(list,1)
print(“list circulated clockwise by 1:”, mylist)
mylist= circulate(list, 2)
print(“List circulated clockwise by 2:”, mylist)
mylist= circulate(list, 3)
print(“List circulated clockwise by 3:”, mylist)
mylist= circulated(list, 4)
print(“List circulated clockwise by 4:”, mylist)
Output:
Original list: [1,2,3,4,5]
list circulated clockwise by1:[2,3,4,5,1]
list circulated clockwise by 2:[3,4,5,1,2]
list circulated clockwise by 3:[4,5,1,2,3]
list circulated clockwise by 4:[5,1,2,3,4]

166
Problem Solving and Python Programming 2020

Here list passed as parameter to function (circulate), this list is circulated based on value the
value.
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.
Example Program:
stulist = [‘Rama’, ‘Chennai’, 2018, ‘CSE’, 92.7]
print ‘Initial list is : ‘, stulist
del stulist[1]
print ‘Now the list is : ‘, stulist
Output:
Initial list is : [‘Rama’, ‘Chennai’, 2018, ‘CSE’, 92.7]
Now the list is : [‘Rama’, 2018, ‘CSE’, 92.7]
pop() and remove() methods can also be used to delete list elements.
4.2 TUPLES
Tuple is a collection sequence of values of different types. Unlike lists, tuple values are
indexed by integers. The important difference is that tuples are immutable. Tuples are created
using parenthesis (). The important points to be noted are
i) The values in tuples can be any type and they are indexed by integers
ii) A type is a comma-seperated list of values.
Example:
>>>t=’a’,’b’,’c’,’d’,’e’
Creation of tuples:
i) Create a tuple with a single element.
>>>t1= ‘a’
>>>type(t1)
<class ‘tuple’>
>>>t2=(‘a’)
>>>type(t2)

167
Problem Solving and Python Programming 2020

<class ‘str’>
ii) A tuple can be created using the built-in function tuple. It can create an empty tuple
with no argument.
>>>t= tuple()
>>>t
()
iii) A tuple built-in- functions can be used to create a tuple with sequence of arguments.
>>>t= tuple(‘computer’)
>>>t
(‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’)
Operators on tuple:
i) Bracket operator
ii) Slice operator
iii) Relational operator
i) Bracket operator
Bracket operator indexes an element.
>>>t= (‘c’,’o’,’m’,’p’)
>>>t[0]
‘c’
>>>t[3]
‘p’
ii) Slice operator
Slice operator selects a range of elements.
>>>t[0:3]
(‘c’,’o’,’m’)
iii) Relational operator
→The relational operators work with tuples and other sequences.
→Python starts by comparing the first element from each sequence.
→If they are equal, it goes on to the next elements and so on, until it finds elements that
differ.

168
Problem Solving and Python Programming 2020

→Subsequent elements are not considered.


Example:
>>>(5,8,2)<(5,10,6)
True
>>>(3,2,500000)<(3,8,5)
True
4.2.1 Tuple assignment
Python has a very powerful tuple assignment feature that allows a tuple of variables on
the left of an assignment to be assigned values from a tuple on the right of the assignment.
Example 1:
>>>a,b= 5,10
>>>a
5
>>>b
10
Example 2:
>>>a,b= minmax(‘abcd’)
>>>a
‘a’
>>>b
‘d’
The requirement is that the number of variables on the left must match with the number of
elements in the tuple.
>>>a,b= 1,2,3
valueError: too man values to un pack
>>>[x,y] = [3,4]
>>>x
3
>>>y
4

169
Problem Solving and Python Programming 2020

→The right side can be any kind of sequence (string, list or tuple).
Example:
To split an email address into a username and a domain consider the following
>>>addr=’[email protected]
>>>uname,domain= addr.split(‘@’)
Here split is a keyword, the return value from split is a list with two elements and the first
element is assigned to username, the second to domain
>>>uname
‘effie’
>>>domain
‘python.org’
4.2.2 Tuples as return values
A function can return only one value, but if the value is a tuple, it can return multiple
values. The built-in function divmod takes two arguments and returns a tuple of two values, the
quotient and the remainder. Here the type of returning a values are
i)It can store the result as a tuple.
>>>t= divmod(13,4)
>>>t
(3,1)
ii) To store the elements separately, use tuple assignment.
>>>Q,R= divmod(13,4)
>>>Q
3
>>>R
1
iii) A function can return a tuple. The built-in function def minmax(t) is used to find the
largest and smallest elements of a sequence and can return a tuple of two values.
def minmax(t):
return min(t),max(t)

170
Problem Solving and Python Programming 2020

→max and min are built-in functions that find the largest and smallest elements of the
sequence.
→minmax computes both the largest and smallest elements and returns a tuple of two
values.
Example Program:
>>>def minmax(t):
return min(t), max(t)
>>>minmax([6,3,7,12])
(3,12)
>>>minmax(‘abcd’)
(‘a’,’d’)
4.2.3 Accessing values
To access the tuple elements slicing (bracket operator [ ]) operator along with index or
indices is used.
Example Program:
t1 = (‘C’, ‘C++’, ‘python’, 1999, 2018);
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

171
Problem Solving and Python Programming 2020

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.
Example Program:
t1 = (‘C’, ‘C++’, ‘python’, 1999, 2018);
print t1
del t1
print “After deleting : “
print t1
Output:
(‘C’, ‘C++’, ‘python’, 1999, 2018)
After deleting:
Traceback (most recent call last):
File “main.py”, line 5, in
print t1
NameError: name ‘t1’ is not defined
4.2.5 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

172
Problem Solving and Python Programming 2020

Output:
(‘A’, ‘b’, ‘c’, ‘d’, ‘e’)
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.6 Built-in functions with tuple
The built-in functions with tuples are given below.
i) all(): Return True if all elements of the tuple are true (or if the tuple is empty).
ii) any():Return True if any element of the tuple is true. If the tuple is empty, return False.
iii) enumerate():Return an enumerate object. It contains the index and value of all the items of
tuple as pairs.
iv) len():Return the length (the number of items) in the tuple.
v) max():Return the largest item in the tuple.
vi) min():Return the smallest item in the tuple
vii) sorted():Take elements in the tuple and return a new sorted list (does not sort the tuple
itself).
viii) sum():Return the sum of all elements in the tuple.
4.2.7 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)
>>> (0, 1, 2) < (0, 3, 4)
True
4.3 Dictionaries
Dictionary is a collection that shows values along with key,the sequence of such key and
value pair is separated by commas, these pairs are sometimes called entries or items,all the
entries are enclosed by {}.A colon seperates key and its values.
→ Dictionaries in Python are implemented using hash table. It is an array whose indexes
are obtained using a hash function on the keys.

173
Problem Solving and Python Programming 2020

→Dictionary is a mutable list.


→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.
Example1:
>>>d={1:apple’,2:’ball’}
>>>d
{1:apple’,2:’ball’}
>>>d[1]
apple
>>>d[2]
Ball
Example2:
>>>d={‘name’,:’ABCD’,’phoneno’,:04652}
>>>d[name]
ABCD
>>>d[phone no]
04652
Example3:
>>>for key , val in d.items():
print (val:key)
name: ABCD
phoneno: 04652
The following code is a simple example which creates an empty dictionary.
mydict = {}
print mydict
Output:
{}
4.3.1 Dictionary –Operations and Methods.
The following dictionary operations and methods are used in python programming.

174
Problem Solving and Python Programming 2020

i) dict()
ii) dict(s)
iii) len()
iv) max()
v) min()
vi) all()
vii) sorted()
viii) any()
ix) pop()
x) copy()
xi) key()
xii) values()
xiii) update()
xiv) clear()
i) dict() : It creates a new, empty dictionary.
>>>cse=dict()
>>>cse
{}
ii) dict(s): It creates a new dictionary with key-value.
>>>cse=dict(s)
iii) len(): It counts the number of key value pairs.
>>>cse={‘name’:’ABC’,’age’:20}
>>>len(cse)
2
iv) max(): It returns the maximum key in dictionary.
>>>max(xse)
2
v) min(): It returns the minimum key in dictionary.
>>>min(cse)
1

175
Problem Solving and Python Programming 2020

vi) all(): It returns true if all keys are true.


>>>all(cse)
True
vii) sorted(): It sort keys in order.
>>>sorted(cse)
[age’,’name’]
viii) any(): It returns true if any key is true
>>>any(cse)
True
ix) pop(): It removes particular item from dictionary.
>>>cse.pop(age)
>>>cse
{‘name’:’ABC’}
x) dict.copy(): It copies dictionary into new dictionary.
>>>cse={‘name’:’ABC’,’age’:’20’}
xi) dict.key(): It returns keys in dictionary
>>>dict.key(cse)
‘name’,’age’
xii) dict.values(): It returns values in dictionary.
>>>dict.values(cse)
‘ABC’,20
xiii) dict.update(): It adds dictionary key-value pairs to dictionary.
>>>dict.update(cse,”address”:”xyz”)
>>>cse
{‘name:’’ABC’,’age’:220,”address’:”xyz}
xiv) dict.clear(): It clears dictionary.
>>>dict.clear(cse)
>>>cse
{}

176
Problem Solving and Python Programming 2020

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.
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.
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 10 is
assigned for all keys. Each item is accessed iteratively using for loop that iterate though each key
in a dictionary.
Example Program:
marks={}.fromkeys([‘Math’,’English’,’Science’],10)
print marks
for item in marks.items():
print item
print list(sorted(marks.keys()))
Output:
{‘Maths’: 10, ‘Science’: 10, ‘English’: 10}
(‘Maths’, 10)
(‘Science’, 10)
(‘English’, 10)
[‘English’, ‘Maths’, ‘Science’]
4.3.5 Reverse lookup
Lookup is the process of finding the corresponding value for the given key from
dictionary. It’s easy to find the value given a key to a Python dictionary.

177
Problem Solving and Python Programming 2020

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.
Example Program:
def getvalue(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 getvalue(squares,4)
Output:
2
4.3.6 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.
Example Program:
def invertdict(d):
newdict = {}
for k, v in d.iteritems():
newdict.setdefault(v, []).append(k)
return newdict
d = { ‘child1’: ‘A1’,
‘child2’: ‘A1’,
‘child3’: ‘parent2’,
‘child4’: ‘parent2’,
}

178
Problem Solving and Python Programming 2020

print invertdict(d)
Output:
{‘parent2’: [‘child3’, ‘child4’], ‘A1’: [‘child1’, ‘child2’]}
4.4 ADVANCED LIST PROCESSING
.The list comprehension is the advanced list processing is given below.
4.4.1 List comprehensions
List comprehension is an elegant and concise way to create new list from existing list in
python. List comprehension process is described by series of keywords.
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 oldlist if filter(i)]

newlist 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.
A list comprehension consists of the following parts:
i) An input sequence.
ii) Variable representing members of the input sequence.
iii) An optional predicate expression.
iv) An Output expression producing elements of the output list from members of the
input sequence that satisfy the predicate.
Example Program1:
>>>a=[11,22,33,44]
>>>b=[x*2 for x in a]
>>>b
[22,44,66,88]

179
Problem Solving and Python Programming 2020

Example Program2:
>>>names=[‘alice’,’bob’,’charly’]
>>>b=[ x.upper() for x in names]
[‘ALICE’,’BOB,’CHARLY]
>>>c=[x.capitalize() for x in names]
>>>c
[‘Alice’,’Bob’,’Charly’]
Example Program3:
>>>vowels=(‘a’,’e’,’i’,’o,’u’)
>>>t=’hello’
>>>[c for c in t if c in vowels]
[‘e’,’o’]
Example Program4:
>>>a=[1,2,3,4]
>>>[x**2 for x in a]
[1,4,9,16]
Example Program5:
>>>a= [10,5,0,-5,-10]
>>>[x for x in a if x>0]
[10,5]
>>>[x for x in a if x<0]
[-5,-10]

4.5 ILLUSTRATIVE PROGRAMS


4.5.1 Insertion sort
def insertionsort(a):
for index in range(1,len(a)):
currentvalue=a[i]
position=i
while position>0 and a[position-1]>currentvalue:

180
Problem Solving and Python Programming 2020

a[position]=a[position-1]
position=position-1
a[position]=currentvalue
list=[50,60,40,30,20,70]
print( “Original list is:”,list)
insertionsort(list)
print(”List after insert:”,a)
Output:
Original list is: =[50,60,40,30,20,70]
List after insert:[20,30.40,50,60,70]

4.5.2 Selection sort


def selectionSort(alist):
for i in range(len(alist)-1,0,-1):
pos=0
for location in range(1,i+1):
if alist[location]>alist[pos]:
pos= location
temp = alist[i]
alist[i] = alist[pos]
alist[pos] = temp
alist = [54,26,93,17,77,31,44,55,20]
selectionSort(alist)
print(alist)
Output:
[17, 20, 26, 31, 44, 54, 55, 77, 93]
4.5.3 Merge sort
def mergesort(a):
if len(a)>1:
mid=len(a)//2

181
Problem Solving and Python Programming 2020

left=a[:mid]
right=a[mid:]
mergesort(left)
mergesort(right)
i=0
j=0
k=0
while i<len(left) and j<len(right):
if left[i]<right[j]:
a[k]=left[i]
i=i+1
else:
a[k]=right[j]
j=j+1
k=k+1
while i<len(left):
a[k]=left[i]
i=i+1
k=k+1
while j<len(right):
a[k]=right[j]
j=j+1
k=k+1
list=[50,60,40,20,70,100]
print ("Original list is:" ,list)
mergesort(list)
print ("Sorted list is:",list)

Output:
Original list is: [50, 60, 40, 20, 70, 100]

182
Problem Solving and Python Programming 2020

Sorted list is: [20, 40, 50, 60, 70, 100]


4.5.4 Histogram
def histogram(items):
for n in items:
output=’’
times=n
while (times>0):
output+=’*’
times=times-1
print(output)
histogram([2,3,4,3,2])
Output:
**
***
****
***
**

183
Problem Solving and Python Programming 2020

PART A (2 Marks with Answers)


1. What is a list? How list differs from tuple? (JANUARY 2018)
A list is an ordered set of values, where each value is identified by an index. The values
that make up a list are called its elements. Lists are similar to strings, which are ordered sets of
characters, except that the elements of a list can have any type.
The syntax for expressing literals of type list is similar to that used for tuples, the
difference is that we use square brackets rather than parenthesis. Lists are mutable, tuples are
immutable.
2. How to slice a list in python? (JANUARY 2018)
The values stored in a list can be accessed using slicing operator with indices starting at
0 in the beginning of the list and ending with -1.
Syntax:
listname[start:finish-1]
3. What are the string operators?
String contains the slicing operator and the slicing with step size parameter is used to
obtain the sub set of a string. It also contain concatenation ‘+’,’in’ and repetition ‘*’ operators.
4. Mention any 5 list methods.
i) sort()
ii) pop()
iii) index()
iv) insert
v) remove()
vi)append()
vii)extend ()
5. State the difference between lists and dictionary.
List is a mutable type meaning that it can be modified whereas dictionary is immutable.
Dictionary is not ordered and it requires that the keys are hashable whereas list can store a
sequence of objects in a certain order.

184
Problem Solving and Python Programming 2020

6. What is List mutability in Python? Give an example.


Python represents all its data as objects. Some of these objects like lists and dictionaries
are mutable, i.e., their content can be changed without changing their identity. Other objects like
integers, floats, strings and tuples are objects that cannot be changed.
Example:
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers [17, 5]
7. What is aliasing in list? Give an example.
Aliasing is a circumstance where two or more variables refer to the same object.
Example: If a refers to an object and we assign b = a, then both variables refer to the same
object.
>>> a = [1, 2, 3]
>>> b = a
>>> b is a True
8. Define cloning in list.
In order to modify a list and also keep a copy of the original, it is required to make a copy
of the list itself, not just the reference. This process is called cloning.
9. Explain List parameters with an example.
Passing a list as an argument actually passes a reference to the list, not a copy of the list.
For example, the function head takes a list as an argument and returns the first element.
def head(list):
return list[0]
10. Write a program in Python to delete first element from a list.
def deleteHead(list):
del list[0]
Exmple:
>>> numbers = [7, 2, 3]
>>> deleteHead(numbers)
>>> print numbers [2, 3]

185
Problem Solving and Python Programming 2020

11. How will you change the elements of Python list?


The elements of Python list can be replaced, inserted and removed (List is a mutable data
structure). 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.
12. What is the benefit of using tuple assignment in Python?
It is often useful to swap the values of two variables. With conventional assignments a
temporary variable would be used. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
Using tuple assignment we can easily swap
>>> a, b = b, a
13. How to create copy of a list?
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.
14. Define dictionary with an example.
A dictionary is an associative array. Any key of the dictionary is mapped to a value. The
values of a dictionary can be any Python data type. So dictionaries are unordered key-value
pairs.
Example:
>>> eng2sp = {} # empty dictionary
>>> eng2sp[’one’] = ’one’
>>> eng2sp[’two’] = ’two’
15. How to return tuples as values?
A function can only return one value, but if the value is a tuple, the effect is the same as
returning multiple values. For example, if we want to divide two integers and compute the
quotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute
them both at the same time.
>>> t = divmod(7, 3)

186
Problem Solving and Python Programming 2020

>>> print t (2, 1)


16. How do you remove duplicates from a list?
Steps:
(i) sort the list.
(ii) scan the list from the end.
(iii) while scanning from right-to-left, delete all the duplicate elements from the list
17. Define dictionary methods with an example.
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), method syntax eng2sp.keys() is used.
>>> eng2sp.keys() [’one’, ’three’, ’two’]
18. Define List Comprehension.
It provides a compact way of mapping a list into another list by applying a function to
each of the elements of the list.
19. Write a Python program to swap two variables.
x = 50
y = 100
print('The value of x after swapping: ',x)
temp = x
x=y
y = temp
print('The value of y after swapping: ',y)
20. How many kinds of sequences are supported by Python?
Python supports 7 sequence types. They are str, list, tuple, unicode, bytearray, xrange, and
buffer.
21. Solve
a)[1] * 4 and
b) [1, 2, 5] * 3.
>>> [01] * 4 [1, 1, 1, 1]
>>> [1, 2, 5] * 3 [1, 2, 5, 1, 2, 5, 1, 2, 5]

187
Problem Solving and Python Programming 2020

22. Let list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’].


Find a) list[1:3] b) t[:4]
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’h’]
>>> list[1:3] [’b’, ’c’]
>>> list[:4] [’a’, ’b’, ’c’, ’d’]
23. Write a program in Python returns a list that contains all but the first element of the
given list.
def tail(list):
return list[1:]
Here’s how tail is used:
>>> numbers = [1, 2, 3]
>>> rest = tail(numbers)
>>> print rest [2, 3]
24. List two dictionary operations.
i) Del -removes key-value pairs from a dictionary.
ii) Len -returns the number of key-value pairs.

25. Compare lookup and reverse lookup.


Lookup is the process of finding the corresponding value for the given key from
dictionary. It's easy to find the value given a key to a python dictionary. value=dict[key]
Whereas, reverse lookup is the process of finding the key for a given value.

26. Write the syntax for list comprehension.


The basic syntax is [ expression for item in list if conditional]

27. Define key- value pairs.


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.

188
Problem Solving and Python Programming 2020

28. Relate Strings and Lists. (JANUARY 2019)


• String is a sequence of characters and a List is a sequence of values, but a list of
characters is not same as string.
• To convert from a string to a list of characters list can be used.
>>>S=’Python’
>>>T=list(S)
>>>print T
[‘P’,’y’,’t’,’h’,’o’,’n’]

29. Give a function that can take a value and return the first key mapping to that value in a
dictionary. (JANUARY 2019)

def reverse_lookup(d,v):
for k in d:
if d[k]==v:
return k
raise Value Error
30. How will you update list items? Give one example. (JANUARY 2020)
List will be updated using index value.
Example:
>>>a=[1,2,3]
>>>a[0]=10
>>> print(a)
[10,2,3]
31. Can function return tuples? If yes give example. (JANUARY 2020)
Yes function return tuples.
Example:
def add(a,b)
return(a+b)
add(3,2)

189
Problem Solving and Python Programming 2020

PART B (Possible Questions)


1. Explain the different ways to create a list with suitable examples.
2. How are elements of a list reversed? Explain.
3. What is list? How will you create list? Explain with neat program.
4. Define dictionary. Explain the various operation s of dictionary with an example.
5. What do you mean by tuple? How will you create a truple? Explain.
6. Explain the following
i) Aliasing
ii) Cloning a list
7. How is an empty list and list with six integers, ie 30,35,40,90,95 and 100 created?
8. List and clarify the operators supporting lists.
9. Explain the supporting inbuilt functions used to create lists.
10. Write a program to pass a list to a function and return it in the reverse order.
11. i)What is a dictionary in python? Give example. (4) (JANUARY 2018)
ii) Appraise the operations for dynamically manipulating dictionaries. (12)
12.i)Write a python program to perform linear search on a list.(8) (JANUARY 2018)
ii) Write a python program to store n numbers in a list and sort the list using selection sort. (8)
13.i)Discuss the different options to traverse a list. (8)
ii)Demonstrate the working of +,* and slice operators in python .(8) (JANUARY 2019)
14. i)Compare and contrast tuples and list in python. (4)
ii)Write a script in python to sort n number using selection sort.(12) (JANUARY 2019)
15.i)Define Dictionary in Python. Do the following operations on dictionaries.(10)
i) Initialize two dictionaries and create a new dictionary with key value pairs.
ii) Compare the two dictionaries with master key and print missing keys.
iii)Find keys that are in first and not in second dictionary.
iv) Find same keys in two dictionaries.
v)Merge two dictionaries and create a new dictionary using a single expression.
ii)What is list comprehension in python? Explain with example. (6) (JANUARY 2020)
16.i)What is tuple in python? How does it differ from list?(8)
ii)Write a python program t sort n numbers using mergesort.(8) (JANUARY 2020)

190
Problem Solving and Python Programming 2020

PART C (Possible Questions)


1 .Write a Python program to duplicate all the elements in a list.
2. Write Python program for the following.
a. Merge sort
b. Selection sort
3. Write a Python program for palindrome using functions and list.
4. Create a list of six elements. Pass the list to a function and compute the average of six
numbers.
5. Write a Python program to create a list to store the names of colors and return size of list.
6. Write a Python program to put even and odd elements in a list into two different lists.
7. Write a Python program to remove the duplicate items from a list.
8. Write a Python program to multiply two matrices.
9. Write a Python program to count the frequency of words appearing in a string using a
dictionary.
10. Write a Python program to add and remove a key-value pair to the dictionary.

191
Problem Solving and Python Programming 2020

Additional Programs
1. Python program to find the largest number in a list.
a=[]
n=int(input("Enter the number :"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:",a[n-1])
Output:
Enter the number :3
Enter element:33
Enter element:569
Enter element:73
Largest element is: 569
2. Python program to put even and odd elements in a list into two different lists.
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
even=[]
odd=[]
for j in a:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print("The even list",even)
print("The odd list",odd)

192
Problem Solving and Python Programming 2020

Output:
Enter number of elements:5
Enter element:69
Enter element:45
Enter element:46
Enter element:28
Enter element:457
The even list [46, 28]
The odd list [69, 45, 457]
3. Python program to remove the duplicate items from a list.
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
a.append(element)
b = set()
unique = []
for x in a:
if x not in b:
unique.append(x)
b.add(x)
print("Non-duplicate items:")
print(unique)
Output:
Enter the number of elements in list:5
Enter element1:100
Enter element2:100
Enter element3:220
Enter element4:220
Enter element5:220

193
Problem Solving and Python Programming 2020

Non-duplicate items:
[100, 220]
4. Python program to add a key-value pair to the dictionary.
key=int(input("Enter the key (int) to be added:"))

value=int(input("Enter the value for the key to be added:"))

d={}

d.update({key:value})

print("Updated dictionary is:")

print(d)

Output:
Enter the key (int) to be added:12
Enter the value for the key to be added:34
Updated dictionary is:
{12: 34}
5. Python program to concatenate two dictionaries in to one.
d1={'A':1,'B':2}

d2={'D':3}

d1.update(d2)

print("Concatenated dictionary is:")

print(d1)

Output:
Case 1:
Concatenated dictionary is:
{'A': 1, 'D': 3, 'B': 2}
6. Python program to check if a given key exists in a dictionary or not.
d={'A':1,'B':2,'C':3}

key=raw_input("Enter key to check:")

194
Problem Solving and Python Programming 2020

if key in d.keys():

print("Key is present and value of the key is:")

print(d[key])

else:

print("Key isn't present!")

Output:
Enter key to check: A
Key is present and value of the key is:
1
7. Python program to sum all the items in a dictionary.
d={'A':100,'B':540,'C':239}

print("Total sum of values in the dictionary:")

print(sum(d.values()))

Output:
Total sum of values in the dictionary:
879
8. Python program to multiply all the items in a dictionary.
d={'A':100,'B':100,'C':239}

tot=1

for i in d:

tot=tot*d[i]

print(tot)

Output:
2390000
9. Python program to remove the given key from a dictionary.
d = {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")

195
Problem Solving and Python Programming 2020

print(d)
key=raw_input("Enter the key to delete(a-d):")
if key in d:
del d[key]
else:
print("Key not found!")
exit(0)
print("Updated dictionary")
print(d)
Output:
Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):c
Updated dictionary
{'a': 1, 'b': 2, 'd': 4}
10. Python program to count the frequency of words appearing in a string using a
dictionary.
test_string=raw_input("Enter string:")
l=[]
l=test_string.split()
wordfreq=[l.count(p) for p in l]
print(dict(zip(l,wordfreq)))
Output:
Enter string: hello world program world test
{'test': 1, 'world': 2, 'program': 1, 'hello': 1}

196
Problem Solving and Python Programming 2020

CHAPTER 5

FILES, MODULES, PACKAGES

Files and exception: text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative programs:
word count, copy file.

197
Problem Solving and Python Programming 2020

198
Problem Solving and Python Programming 2020

FILES, MODULES, PACKAGES


5.1 FILES AND EXCEPTION
Files:
File is a named location on disk to store the related information. A collection of data or
information that has a name is called the file name. All information stored in a computer must be
in a file.
Types of files:
i) Data files
ii) Text files
iii) Program files
iv) Directory files
5.1.1 Text files
Text file is a sequence of characters stored on a permanent medium like hard drive, flash
memory (or) CD-ROM. In addition to printable characters, the text file contains non printing
characters. So a text file contain letters (a-z/A-Z), numbers (0-9), special symbols ($,#),non
printing characters(\n,\t,\b) etc. Text file should be saved with the extension .txt.
5.1.2 File operations
In Python, a file operation takes place in the following order.
i) Opening the file
ii) Reading and writing (perform operation)
iii) Closing the file
i) Opening the file
When the user wants to read or write to a file, user needs to open it first. Python has a
built-in function open () to open a file.
Syntax:
fileobject=open(“filename”, ”access mode”)
The parameters are explained below:
filename →The filename 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,

199
Problem Solving and Python Programming 2020

write, append, etc).


Example:
>>>f=open(“test.txt”,”w”)
File opening modes:
There are various modes while opening a file. They are,
Modes Description
Opens a file for reading only. The file pointer is placed at the beginning of
r
the file.
Opens a file for reading only in binary format. The file pointer is placed at
rb
the beginning of the file. This is the default mode.
Opens a file for both reading and writing. The file pointer placed at the
r+
beginning of the file.
Opens a file for both reading and writing in binary format. The file pointer
rb+
placed at the beginning of the file.
Opens a file for writing only. Overwrites the file if the file exists. If the
w
file does not exist, creates a new file for writing.
Opens a file for writing only in binary format. Overwrites the file if the
wb
file exists. If the file does not exist, creates a new file for writing.
Opens a file for both writing and reading. Overwrites the existing file if
w+ the file exists. If the file does not exist, creates a new file for reading and
writing.
Opens a file for both writing and reading in binary format. Overwrites the
wb+ existing file if the file exists. If the file does not exist, creates a new file
for reading and writing.
Opens a file for appending. The file pointer is at the end of the file if the
a file exists. If the file does not exist, it creates a new file for writing.

Opens a file for appending in binary format. The file pointer is at the end
ab
of the file if the file exists. If the file does not exist, it creates a new file

200
Problem Solving and Python Programming 2020

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

The file object attributes:

Attribute Description
Returns true if the file is closed, otherwise
file.closed
false.
Returns the file access mode with which file
file.mode
was opened.
file.name Returns name of the file.
ii) Reading and writing files
Python provides read () and write () methods to read and write files through file object
respectively.
Reading files:
The read() method read the file contents, from opened file. To read the content of file, the
file must be opened in read mode (r).There are 4 methods for reading files.
i ) Reading a file using read(size) method
ii) Reading a file using for loop
iii) Reading a file using readline() method
iv) Reading a file using readlines() method
The file test.txt contains
problem solving and python programming.
Introduction to python
i) Reading a file using read(size) method
201
Problem Solving and Python Programming 2020

The read(size) method is used to read in size number of data.If the size parameter is not
specified, it reads and returns up to the end of file.
Syntax:
fileobject . read([size])
Example:
f=open(“test.txt”, “r+”)
S=f.read(15);
print(“Read string is:”,S)
f.close()
Output:
Read string is: problem solving
ii) Reading a file using for loop
A file can be read using for loop. This method is efficient and fast.
Syntax:
for loopvariable in fileobject:
print(loopvariable)
Example Program:
f=open(“test.txt”, “r+”)
for i in f:
print(i)
f.close()
Output:
Problem solving and python programming
Introduction to python
iii) Reading a file using readline() method
The readline() method is used to read individual line of a file. It reads a file till the
newline(\n) character is reached (or) end of file is reached.
Syntax:
fileobject . readline()
Example Program:

202
Problem Solving and Python Programming 2020

f=open(“test.txt”, “r+”)
f.readline()
f.close()
Output:
Problem solving and python programming
iv) Reading a file using readlines() method
The readlines() method is used to read all the lines of file at a time.
Syntax:
fileobject.readlines()
Example Program:
f=open(“test.txt”, “r+”)
f.readlines()
f.close()
Output:
Problem solving and python programming
Introduction to python
Writing files:
The write() method is used to write the contents into the file. To write the file contents,
the file must be opened into following mode.
w-writing mode
a-appending mode
x-exclusive creation
The ‘w’ mode will overwrite into the file if already exists. So all previous data’s are erased.
Syntax:
fileobject . write(string)
Example Program:
f=open(“test.txt”, “r+”)
f.write(“Welcome to python”)
f.close()
iii) Closing the file

203
Problem Solving and Python Programming 2020

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 can be done. Python closes a file
automatically when the reference object of a file is reassigned with another file. The syntax of
close () function is given below.
Syntax:
fileobject.close()
Example Program:
f1=open(“test.txt”,”w”)
print(“Name of file is:”,f1.name)
print(“closed or not:”,f1.closed)
print(“opening mode is:”,f1.mode)
f1.close()
Output:
Name of file is:test.txt
closed or not:False
opening mode is:w
5.1.3 Format Operator
write() function takes the argument as a string . To put other values in a file, it must be
converted to strings. It is done by 2 methods:
i) str() method is used to convert other values into string.
Example Program:
>>>x=52
>>>f.write(str(x))
52
ii) Format operator is an % operator that converts other values into string.
with integers, % is considered as modulus operator
with strings,% is considered as format operator

Example Program:
>>>x=15

204
Problem Solving and Python Programming 2020

>>>”%d”%x
15
%d is formatted as decimal integer.
Format sequence in string:
Format sequence can appear anywhere in the string
Example Program:
>>>computers=10
>>>’I have bought %d computers’, %computers
Output:
I have bought 10 computers
More than one format sequence:
If there is more than one format sequence, second argument must be tuple.
Example Program:
>>>”In %d years, I have bought %g%s”.%(2,3.0,’computers’)
In 2 years, I have bought 3.0 computers
In the above program:
→%d is formatted to integer
→%g is formatted to floating point number
→%s is formatted to string.
→Number of elements in tuple and number of format sequences must be same.
5.2 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 script other languages.
Command line argument in python can be processed by using two modules.
i) sys module
ii) argparse module
i) sys module
Sys module is used to access the command line arguments through sys.argv. The sys
module is used for two purposes.
i) sys.argv is a list in Python, which contains the command line arguments passed to the script.

205
Problem Solving and Python Programming 2020

ii) len(sys.argv) is used to count the number of arguments


There are three steps followed in sys module
i) Import the sys module
ii) We can use sys.argv for getting the list of command line arguments.
iii) Use len(sys.argv) for getting length of command line arguments.
Example Program:
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
Output:
Number of arguments: 4
Argument List: [‘test.py’, ‘arg1’,’arg2’,’arg3’]
ii) argparse module
argparse module is used to access command line arguments. It includes tools for building
command line arguments. There are three steps followed in arg parse module.
i) Import argparse module
ii) Use ArgumentParser for parsing command line arguments
iii) Use parseargs() method to parse command line arguments.
Example Program:
Import argparse
Parser=argparse.ArgumentParser()
Parser.parseargs()
Output:
>>>python cmdline.py –h
Usage:cmdline.py[-h]
Optional arguments
-h,--help show message

206
Problem Solving and Python Programming 2020

5.3 ERRORS AND EXCEPTIONS


5.3.1 Errors
Errors or mirrors in a program are often referred to as bugs. Error is mistakes in the
program, which are created by fault of the programmer.
Debugging:
Debugging is the process of finding and eliminating errors.

Errors

Syntax error Runtime error Logical error

Missing Division Access Using


Mis Using operator
spelling of colon by zero not
wrong precedence
keyword ,comma defined
variable wrong
identifier
name

Fig: 5.1: Types of errors


Types of errors:
i) Syntax errors
ii) Runtime errors
iii) Logical error
i) Syntax errors
Syntax error occurs when the program is not following the proper structure (syntax).
If syntax errors occur then python display error message and exit without continuing execution
process.

207
Problem Solving and Python Programming 2020

Some of syntax errors are:


→Misspelling keyword
→Incorrect indentation
→Missing of colon, comma
→Leaving a keyword
→Putting a keyboard in wrong place
Here are some examples of syntax errors in Python:
a=5
b=20
if a<b
print ‘a is greater’
Error Message:
File “main.py”, line 3
if a<b
^
ii) Runtime errors
Runtime errors occur during execution of program. It is also known as dynamic errors.
Some of runtime errors are:
→Division by Zero
→Access not defined identifier
→Access not defined file
Example:
>>>b= [1,2,3,4]
>>>a
Runtime Error:’a’ is not defined
>>>a=5
>>>b=10
>>>a/b
Runtime Error:’Division by Zero’

208
Problem Solving and Python Programming 2020

iii) Logical errors


Logical error occurs 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
logical errors are:
→ Using the wrong variable name
→ Indenting a block to the wrong level
→Using integer division instead of floating-point division
→Using wrong operator precedence
→ Making a mistake in a Boolean expression
→Off-by-one and other numerical errors
Example:Addition of two numbers
>>>x=10
>>>y=20
>>>z=x-y #Logic error
>>>print z
-10
Here, parentheses are missing. So we get wrong result.
5.3.2 Exceptions
An exception is an error that occurs during execution of a program. It is also called as run
time error. 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>

209
Problem Solving and Python Programming 2020

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.
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.
210
Problem Solving and Python Programming 2020

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

5.4 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. If an error is encountered, a try block code
execution is stopped and control transferred down to except block.

Try Raise Except

Exception Raise the Catch if exception


occurs
may occur Exception

Fig 5.2: Exception Handling

211
Problem Solving and Python Programming 2020

Syntax:
try:
statements
----------------

-----------------

Except exception1:

If exception1 occurs execute it.

Except exception2:

If exception2 occurs execute it.

The try statement works as follows.


i) First, the try block (the statement(s) between the try and except keywords) is
executed.

ii) If no exception occurs, the except block is skipped and execution of the try statement
is finished.

iii) If an exception1 occurs rest of try block is skipped, except block1 gets executed.
iv) If an exception2 occurs rest of try block is skipped, except block2 gets executed.
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”
Output:
divide 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.

212
Problem Solving and Python Programming 2020

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!”)
Output (successful):
Please enter the dividend: 12
Please enter the divisor: 2
12 / 2 = 6.000000
Output (unsuccessful-divide by zero error):
Please enter the dividend: 100
Please enter the divisor: 0
The dividend may not be zero!

Output (unsuccessful-value error):


Please enter the dividend: ‘e’
The divisor and dividend have to be numbers!
An except clause may name multiple exceptions as a parenthesized tuple, for example:

213
Problem Solving and Python Programming 2020

... except (RuntimeError, TypeError, NameError):


...#handlercode
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!”)
Output:
Please enter the dividend: 110
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!”)
5.4.1 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 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.
Syntax of two forms of the raise statement are:
raise ExceptionClass(value)
raise Exception

214
Problem Solving and Python Programming 2020

Example:
try:
raise NameError
except NameError:
print(‘Error’)
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 re-raise. 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
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.
5.4.2 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.
try:
age = int(input(“Please enter your age: “))
except ValueError:
215
Problem Solving and Python Programming 2020

print(“Value error occured”)


else:
print(“I see that you are %d years old.” % age)
Output:
Please enter your age:10
I see that you are 10 years old.
Please enter your age:’a’
Value error occured
5.4.3 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”””
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

5. 5 MODULES
Module is a file containing Python definitions and statements. Modules are imported from
other modules using the import command.
i) When module gets imported, Python interpreter searches for module.
ii) If module is found, it is imported.
iii) If module is not found, “module not found” will be displayed.

216
Problem Solving and Python Programming 2020

Modules

Built-in module User defined modules

random math date time

Fig 5.3: Types of modules


5.5.1 Built-in modules
Built-in modules are predefined modules, which is already in python standard library.
Python have the following built-in modules.
i) random
This module generates random numbers. If we want random integer, we use randint function.
Example:
>>>import random
>>>print random . randint(0,5)
1 (or)2 (or) 3 (or)4 (or)5
ii) math
This module is used for mathematical calculations. If we want to calculate square root, we use
the function sqrt.
Example:
>>>import math
>>>math . sqrt(16)
4

217
Problem Solving and Python Programming 2020

>>>math . factorial(4)
24
iii) datetime
This module is used to calculate date and time.
Example:
>>>import datetime
>>>datetime . time()
9:15:20
>>>datetime . date()
21.06.2018
5.5.2 User Defined modules
To create module,write one or more functions in file, then save it with .py extentions.
i) Create a file
def add(a,b):
c=a+b
return c
ii) Save it as sum.py
iii) Import module
>>>import sum
>>>print sum.add(10,20)
5.6 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 tree like hierarchical file directory structure that consists of
modules, sub-packages, sub-sub packages, 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.
Example:
Assume we are creating a package named Animals with some sub packages as shown in
following.

218
Problem Solving and Python Programming 2020

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)

Fig 5.3: Organization of packages and modules


Steps to create a Python package:
i) Create a directory and name it with a package name.
ii) Keep subdirectories (sub packages) and modules in it.
iii) 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.
Method 1:
Consider, we import the display.py module in the above example. It is accomplished by
the following statement.

219
Problem Solving and Python Programming 2020

Syntax:
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.
Syntax:
Animals.Birds.display.displayByName()
Method 2:
On another way, we can import display.py module alone as follows:
Syntax:
from Animals.Birds import display
Then, we can call displayByName() function simply as shown in the following statement:
Syntax:
display.displayByName()
5.7 ILLUSTRATIVE PROGRAMS
5.7.1 Word count
This Program counts the number of words present in a given file.
try:
InFile=open(“test.txt”,’r’)
except IOError:
print “Error:File Not Found”
else:
data=inFile.read()
words=data.split()
print(words)
print “Total number of words are:”,len(words)
Output:
test.txt
I am enjoying python program
[‘I’, ‘am’, ‘enjoying’,’python’,’program’]
Total number of words are:5

220
Problem Solving and Python Programming 2020

5.7.2 Copy files


To copy files in Python, you have to import copy file from shutil library. The copyfile()
function copies the content of source file into destination file.
Example Program:
from shutil import copyfile
sourcefile=input(“Enter the source file name:”)
destfile=input(“Enter the destination file name:”)
copyfile(sourcefile,destfile)
print(“File copied successfully!)
c=open(destfile,’r’)
print(c.read())
c.close()
Output:
f1.txt
Hello Python
Enter the source file name: f1.txt
Enter the destination file name: f2.txt
File copied successfully!
Hello Python

221
Problem Solving and Python Programming 2020

PART A (2 Marks with Answers)

1. Define file.
File is the named location on the system which stores data, information or commands for later
access. It stores the information permanently.
2. Define Text File.
Text files are the types of files that store information in the form of readable and printable
characters. They are the persistent storage.
3. What are the basic file operations in python?
→Opening a file
→Writing to a file.
→Reading from a file
→Closing a file.
4. What are the different types of files?
i) Data files
ii) Text files
iii) Program files
iv) Directory files
5. Write the syntax for opening and closing a file.
Opening a file: fileobject.open(“filename”,mode)
Closing a file: fileobject.close()
6. Write a python program that writes “Hello world” into a file.
f =open("ex88.txt",'w')
f.write("hello world")
f.close()
7. Write a python program that counts the number of words in a file.
f=open("test.txt","r")
content =f.readline(20)
words =content.split()
print(words)
8. What are the two arguments taken by the open() function?
222
Problem Solving and Python Programming 2020

The open function takes two arguments: name of the file and the mode of operation.
Example:
f = open("test.txt","w")
9. What is a file object?
A file object allows us to use, access and manipulate all the user accessible files. It
maintains the state about the file it has opened.

10. What is the difference between readline() and readlines() method.


The readline() method reads a single line from a file.
fileobject.readline()
The readlines() method reads all the lines written in a file at a time.
fileobject.readlines()
11. How will you write files?
The write() method is used to write the contents into the file. To write the file contents,
the file must be opened into following mode.
→w-writing mode
→-appending mode
→x-exclusive creation
Syntax:
fileobject . write(string)
12. What is meant by format operator(%)?
Format operator % is used to convert the other values into string.
Example program:
>>>x=15
>>>”%d”%x
15
%d is formatted as decimal integer.
13. Define 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.Command line argument in python can be
processed by using two modules.
223
Problem Solving and Python Programming 2020

i) sys module
ii) argparse module
14. What is an exception?
Whenever a runtime error occurs, it creates an exception. The program stops execution
and prints an error message.
For example, dividing by zero creates an exception:
print 55/0
ZeroDivisionError: integer division or modulo
15. Define an error. What are its types?
Errors are mistakes in the program, which are created by fault of the programmer. They
are often referred to as bugs.
Types of errors:
iv) Syntax errors
v) Runtime errors
vi) Logical error
16. Define Debugging.
Debugging is the process of finding and eliminating errors.
17. Define Runtime errors.
Runtime errors occur during execution of program. It is also known as dynamic errors.
Some of runtime errors are:
→Division by Zero
→Access not defined identifier
→Access not defined file
18. What are the error messages that are displayed for the following exceptions?
→Accessing a non-existent list item
→Accessing a key that isn’t in the dictionary
→Trying to open a non-existent file
→IndexError: list index out of range
→KeyError: what
→IOError: [Errno 2] No such file or directory: 'filename'

224
Problem Solving and Python Programming 2020

19. How do you handle the exception inside a program when you try to open a non-existent
file?
filename = raw_input('Enter a file name: ')
try:
f = open (filename, "r")
except IOError:
print 'There is no file named', filename
20. How does try and execute work?
The try statement executes the statements in the first block. If no exception occurs, then
except statement is ignored. If an exception of type IOError occurs, it executes the statements in
the except branch and then continues.
21. What is the function of raise statement? What are its two arguments?
The raise statement is used to raise an exception when the program detects an error. It takes
two arguments: the exception type and specific information about the error.
22. What are modules?
A module is simply a file that defines one or more related functions grouped together. To
reuse the functions of a given module, we need to import the module.
Syntax: import <modulename>
23. What is a package?
Packages are namespaces that contain multiple packages and modules themselves. They are
simply directories.
Syntax: from <mypackage> import <modulename>
24. What is the special file that each package in Python must contain?
Each package in Python must contain a special file called __init__.py.
25. Write a python program to count number of lines, words and characters in a text file.
def wordCount():
cl=0
cw=0
cc=0
f=open("ex88.txt","r")

225
Problem Solving and Python Programming 2020

for line in f:
words=line.split()
cl +=1
cw +=len(words)
cc +=len(line)
print('No. of lines:',cl)
print('No. of words:',cw)
print('No. of characters:',cc)
f.close()
26. Write a python script to display the current date and time. ( JANUARY 2018)
>>>import datetime
>>>datetime.time()
9:15:20
>>>datetime.date()
19/5/2018
27. Write a note on modular design. (JANUARY 2018)
A module is simply a file that defines one or more related functions grouped together. To
reuse the functions of a given module, we need to import the module.
Syntax: import <modulename>

28. What is module? Give example. (JANUARY 2019)


Module is a file containing Python definitions and statements. Modules are imported
from other modules using the import command.
Syntax: import <modulename>
Eg. import math
29. Find the syntax error in the code given: (JANUARY 2019)
While True print(‘Hello world’)
Syntax Error: Invalid Syntax
The error is detected at the function print(), since a colon(:) is missing before it.
30. How to use command line arguments in python? (JANUARY 2020)
By using the following system argument
226
Problem Solving and Python Programming 2020

• Sys.argv
• argparse
• getopt
31. Write methods to rename and delete files. (JANUARY 2020)
Delete - remove()
Rename – rename()

227
Problem Solving and Python Programming 2020

PART B (Possible Questions)

1. Explain in detail about Text files.


2. Write a Python program to illustrate the use of command-line arguments.
3. How file is opened and closed?
4. Explain the basic operations in manipulating file.
5. How other values are converted into strings? Or Explain in detail about format operator.
6. How exceptions are handled? Explain in detail.
7. Explain in detail about error and Exceptions.
8. Tabulate the different modes of opening a file and explain the same. (16) (JANUARY 2018)
9. i)Appraise the use of try block and except block in python with syntax (6) (JANUARY 2018)
ii) Explain with an example exceptions with arguments in python. (10)
10.i)Explain the commands used to read and write into a file with examples.(8)
ii)Discuss about the use of format operator in file processing.(8) (JANUARY 2019)
11. Describe how exceptions are handled in python with necessary examples.(16)
(JANUARY 2019)
12.i)What are Exceptions? Explain the method to handle them with example.(8)
ii) Write a python program to count the number of words in a text file.(8) (JANUARY 2020)
13.i)How to merge multiple files into a new file using python.
ii)What are modules in python? How will you import them? Explain the concept by
creating and importing a module. (JANUARY 2020)

228
Problem Solving and Python Programming 2020

PART C (Possible Questions)

1. Write a function that copies a file reading and writing up to 50 characters at a time.
2. Write a Python program to handle multiple exceptions.
3. Write a python program to count number of lines, words and characters in a text file.
4. Write a program to illustrate multiple modules.
5. Write a Python program to append the contents of one file to another file.
6. Write a Python program to count the occurrences of a word in a text file.
7. Write a Python program to count the number of blank spaces in a text file.

229
Problem Solving and Python Programming 2020

Additional Programs

1. Python program to read the contents of a file.


a=str(input("Enter the name of the file with .txt extension:"))
file2=open(a,'r')
line=file2.readline()
while(line!=""):
print(line)
line=file2.readline()
file2.close()
Output:
Contents of file:
Hello world
Output:
Enter the name of the file with .txt extension: data1.txt
2. Python program to count the number of words in a text file.
fname = input("Enter file name: ")
numwords = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
numwords += len(words)
print("Number of words:")
print(numwords)
Output:
Contents of file:
Hello world
Output:
Enter file name: data1.txt
Number of words: 2

230
Problem Solving and Python Programming 2020

3. Python program to count the occurrences of a word in a text file.


fname = input("Enter file name: ")
word=input("Enter word to be searched:")
k=0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
if(i==word):
k=k+1
print("Occurrences of the word:")
print(k)
Output:
Contents of file:
hello world hello
hello
Output:
Enter file name: test.txt
Enter word to be searched:hello
Occurrences of the word:3
4. Python program to append the contents of one file to another file.
name1 = input("Enter file to be read from: ")
name2 = input("Enter file to be appended to: ")
fin = open(name1, "r")
data2 = fin.read()
fin.close()
fout = open(name2, "a")
fout.write(data2)
fout.close()
Output:

231
Problem Solving and Python Programming 2020

Output:
Enter file to be read from: test.txt
Enter file to be appended to: test1.txt
Contents of file test.txt:
Appending!!
Contents of file test1.txt (before appending):
Original
Contents of file test1.txt (after appending):
Original Appending!!
5. Python program to count the number of blank spaces in a text file.
fname = input("Enter file name: ")
k=0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter.isspace):
k=k+1
print("Occurrences of blank spaces:")
print(k)
Contents of file:
he l l o world hello
Output:
Output:
Enter file name: read.txt
Occurrences of blank spaces:5
6. Python program to read a file and capitalize the first letter of every word in the file.
fname = input("Enter file name: ")
with open(fname, 'r') as f:

232
Problem Solving and Python Programming 2020

for line in f:
l=line.title()
print(l)
Output:
Contents of file:
hello world
hello
Output:
Enter file name: read.txt
Hello World
Hello
7. Python program to read the contents of a file in reverse order.
filename=input("Enter file name: ")
for line in reversed(list(open(filename))):
print(line.rstrip())
Output:
Contents of file:
hello world
hello
Output:
Enter file name: read.txt
hello
hello word

233
Problem Solving and Python Programming 2020

234
Problem Solving and Python Programming 2020

ANNA UNIVERSITY
MODEL
QUESTION PAPERS

235
Problem Solving and Python Programming 2020

236
Problem Solving and Python Programming 2020

MODEL QUESTION PAPER –I


(Regulation 2017)
First Semester
Common to All Branches
GE 8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING
Time: 3 Hours Maximum Marks: 100
Answers all Questions
PART – A (10x2=20)
1. Define algorithm.
2. Differentiate pseudo code and flowchart.
3. What is Python?
4. Define keyword? List out any four of the same.
5. Write a program to calculate area and perimeter of circle using function.
6. Is string is mutable or immutable? Justify.
7. Define list and tuples with declarations.
8. Explain various dictionary operations.
9. Explain various modes of file opening.
10. Define exception handling.
PART –B (5 x13=65)
11.a. Explain the basic symbols for constructing a flowchart & discuss about the basic guidelines
for preparing flowchart.(13)
OR
b. i) Write an algorithm to sort a list of numbers in ascending order. (6)
ii) Write a pseudocode to find the sum of the digits of a positive number. (7)
12.a. Briefly discuss about the fundamental of Python.(13)
OR
b. Explain the different types of operators with example. (13)
13.a.i) Explain the type of function arguments in Python.(8)
ii) Write a Python program using function to check given number is odd or even. (5)
OR

237
Problem Solving and Python Programming 2020

b. Briefly discuss about the types of decision making statements. (13)


14. a.What is Python list? Explain the basic list operations with suitable examples.(13)
OR
b.i) Write a Python program to multiply two matrices.(7)
ii) Write a Python program to concatenate two lists.(6)
15. a. Describe in detail about exception handing with necessary examples.(13)
OR
b. i) Write a program to generate Armstrong numbers between two limits.(9)
ii) Write a program to assess if a file closed or not. (4)
PART – C (1x15=15)
16. a. Create a list of six elements. Pass the list to a function and compute the average of six
numbers. (15)
OR
b. Write a program to illustrate multiple modules. (15)

238
Problem Solving and Python Programming 2020

MODEL QUESTION PAPER –II


(Regulation 2017)
First Semester
Common to All Branches
GE8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING
Time: 3 Hours Maximum Marks: 100
Answers all Questions
PART – A (10x2=20)
1. Define programming language.
2. What are the limitations of using flowchart?
3. Write an algorithm for computing greatest of three numbers.
4. Define variable? How will you declare a variable?
5. Write a program to swap the contents of two variable with and without using third
variable.
6. Differentiate break and continue.
7. Differentiate list and string.
8. How will you declare used-defined exception?
9. Write a Python script to display current date and time.
10. Explain the syntax for opening a file.
PART –B (5 x13=65)
11.a What is pseudocode? Explain how it can be designed and write the benefits and
limitations.(13)
OR
b. i) Discuss briefly about the simple strategies for developing an algorithm. (13)
12. a. Write a program to perform addition, subtraction, multiplication, integer division, modulo
division, floor division on two values. (13)
OR
b. Define operator. Explain the different types of operators with example. (13)
13. a. Briefly discuss about the looping techniques in Python with suitable examples.(13)

239
Problem Solving and Python Programming 2020

OR
b. Define recursion. Write a Program for finding factorial of given number. (13)
14. a. Define list. Explain the various techniques to slice the list. (13)
OR
b.i) Define dictionary and its operation in detail.(7)
ii) Explain about the different types of arguments in detail. (6)
15. a .i)Explain in detail about how to read contents from file with example.(6)
ii) Explain in detail about package concepts in python with example. (7)
OR
b. i) Define exception handling? Explain user defined exception handling in detail.(6)
ii) Write a program to count the occurrence of all letters in file. (7)

PART –C (1 x15=15)
16. a. Summarize the difference between algorithm, flowchart and pseudo code.(15)
OR
b. Do the Case study and perform the following operation in tuples i) Maxima ii) minima iii)
sum of two tuples iv) duplicate a tuple v) slicing operator vi) obtaining a list from a tuple
vii) Compare two tuples viii) printing two tuples of different data types.(15)

240
Problem Solving and Python Programming 2020

MODEL QUESTION PAPER –III


B.E./B.Tech. DEGREE EXAMINATION, January 2018
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 building 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)
ii) Outline with an example the assignment operators supported in Python. (8)
(OR)
241
Problem Solving and Python Programming 2020

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)

242
Problem Solving and Python Programming 2020

Question Paper Code: 54009

B.E./B.Tech. DEGREE EXAMINATION, JANUARY 2018


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 an algorithm to accept two numbers, compute the sum and print the result.
3. Name the four types of scalar objects Python has.
4. What is a tuple? How literals of type tuple are written? Give example.
5. Write a Python program to accept two numbers, multiply them and print the result.
6. Write a Python program to accept two numbers, find the greatest and print the result.
7. What is a list? How lists differ from tuples?
8. How to slice a list in Python?
9. Write a Python script to display the current date and time.
10. Write a note on modular design.

PART – B (5×16=80 Marks)

11. a) i) Draw a flow chart to accept three distinct numbers, find the greatest and print the result.
(8)
ii) Draw a flow chart to find the sum of the series 1 + 2+ 3+4+5+….+100. (8)
(OR)
b) Outline the Towers of Hanoi problem. Suggest a solution to the Towers of Hanoi problem
with relevant diagrams. (16)
243
Problem Solving and Python Programming 2020

12. a i) What is a numeric literal? Give examples. (4)


ii) Appraise the arithmetic operators in Python with an example. (12)
(OR)
b)i) Outline the operator precedence of arithmetic operators in Python. (6)
ii) Write a Python program to exchange the value of two variables. (4)
iii) Write a Python program using function to find the sum of first ‘n’ even numbers and .
print the result (6)
13. a) i) Appraise with an example nested if and elif header in Python. (8)
ii) Explain with an example while loop, break statement and continue statement in Python.
(8)
(OR)
b)i) Write Python program to find the factorial of a given number without recursion and with
recursion. (8)
ii) Write a Python program to generate first ‘N’ Fibonacci numbers. (8)
Note : The Fibonacci numbers are 0,1,1,2,3,5,8,13,21,34,….where each number is
the sum of the preceding two.
14. a)i) What is a dictionary in Python? Give example. (4)
ii) Appraise the operations for dynamically manipulating dictionaries. (12)

(OR)
b) i) Write the Python program to perform linear search on a list. (8)
ii) Write a Python program to store ‘n’ numbers in a list and sort the list using
selection sort. (8)
15. a) Tabulate the different modes for opening a file and explain the same. (16)
(OR)
b)i) Appraise the use of try block and except block in Python with syntax. (6)
ii) Explain with an example exceptions with arguments in Python. (10)

244
Problem Solving and Python Programming 2020

Question Paper Code: 25109

B.E./B.Tech. DEGREE EXAMINATION, Dec/Jan 2019


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. Distinguish between algorithm and program.
2. Write an algorithm to find minimum number in a given list of numbers.
3. What are keywords? Give example.
4. State the reason to divide programs into functions.
5. Present the flow of execution for a while statement.
6. Define recursion with example.
7.Relate Strings and Lists.
8. Give a function that can take a value and return the first key mapping to that value in a
dictionary
9. What is module? Give example.
10. Find the syntax error in the code given:
While True print(‘Hello world’)

PART B (5*16= 80 Marks)


11. a. i) Discuss about the building blocks of algorithms. (8)
ii) Write a recursive algorithm to solve towers of Hanoi problem. (8)
(OR)
b. i) Identify the simple strategies for developing an algorithm. (8)

245
Problem Solving and Python Programming 2020

ii)Write an algorithm to insert a card into a list of sorted cards. (8)

12. a. i)Sketch the structure of interpreter and compiler. Detail the difference between them.
Explain how python works in interactive mode and script mode with example. (2+2+4)
ii)Summarize the precedence of mathematical operators in python (8)
(OR)
b.i)Explain the syntax and structure of user defined functions in python with examples. Also
discuss about parameter passing in functions. (12)
ii)Write a python function to swap the values of two variables (4)

13. a) List the three types of conditional statements and explain them (16)
(OR)
b. i)Python strings are immutable, Justify with an example (8)
ii)Write a python code to perform binary search. Trace it with an example of your choice.
14. a.i)Discuss the different options to traverse a list (8)
ii)Demonstrate the working of +,* and slice operators in python (8)
(OR)
b.i)Compare and contrast tuples and list in python (4)
ii)Write a script in python to sort n number using selection sort (12)

15. a.i)Explain the commands used to read and write into a file with examples (8)
ii)Discuss about the use of format operator in file processing (8)

(OR)
b) Describe how exceptions are handled in python with necessary examples (16)

246
Problem Solving and Python Programming 2020

Question Paper Code: 90277

B.E./B.Tech. DEGREE EXAMINATION, NOV/DEC 2019


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. How will you analyze the efficiency of an algorithm.
2. What is the use of Algorithm, Flowchart and Pseudo code in the perspective of problem
solving.
3. Compare interpreter and compiler. What type of translator is used for python?
4. Write a python program to print sum of cubes of the values of n variables.
5. Do Loop statements have else clause? When will it be executed?
6. Write a program to display a set of strings using range() function.
7.How will you update list items? Give an example.
8. Can function return tuples? If yes give example.
9. How to use command line arguments in python?
10. Write method t rename and delete files.
PART B (5*16= 80 Marks)
11.a) i) What is Programming language? What are its types? Explain them in detail with their
advantages and disadvantages(8)
ii) Write a function find_index, which returns the index of a number in the Fibonacci
sequence, if the number is an element of this sequence and return -1 if the number is not
contained in it, call this function using user input and display the result.(8)
OR

247
Problem Solving and Python Programming 2020

b). i) What is recursive function? What are its advantages and disadvantages? Compare it
with iterative function.(6)
ii) Implement a recursive function in python for the sieve of Eratosthenes. The sieve of
Eratosthenes is a simple algorithm for finding all prime numbers up to a specified integer.
It was created by the ancient Greek mathematician Eratosthenes. The algorithm to find
all prime numbers less than or equal to a given integer n:
1)Create a list of integers from two to n:2,3,4,….n
2)Start with a counter i set to 2. (i.e)the first prime number
3)Starting from i+1,count up by I and remove those numbers from the
list,(i.e)2*I,3*I,4*i….
4)Find the first number of the list following i. This is the next prime number
5)Set I to the number found in the previous step
6)Repeat steps 3 and 4 until I is greater than n.
7)All the numbers, which are still in the list are prime numbers (10)

12. a.i)Write a python program to rotate a list by right n times with and without slicing
techniques(4+4)
ii)Discuss about keyword arguments and default arguments in python with examples(4+4)
OR
b)i)Write a python program print the maximum among ‘n’ randomly generate ‘d’ numbers
by storing them in a list(10)
ii)Evaluate the following expression in python
(i)24//6%3
(ii)float(4+int(2.39)%2)
(iii)2 **2**3 (6)
13.a.i)If you are given three sticks, you may or may not be able to arrange them in a triangle. For
example, if one of the sticks is 12 inches long and the other two are one inch long, you will not
be able to get the short sticks to meet in the middle. For any three length, there is a simple test to
see if it is possible to form a triangle: If any of three lengths is greater than the sum of the other
two, then you cannot form a triangle. Otherwise ,you can.
248
Problem Solving and Python Programming 2020

i)Write a function named is – triangle that takes three integers as arguments, and that prints
either “yes” or “no”, depending on whether you can or cannot form a triangle from sticks with
the given lengths. (4)
ii)Write a function that prompts the user to input three stick lengths, converts them to
integers, and uses is – triangle to check whether sticks with the given lengths can form a triangle
(4).
iii)Write a python program to generate all permutations of a given string using built-in
functions. (8)
OR
b.i)Compare list and array with example.Can list be considered as an array?justify (6)
ii)Write a python function are Anagram1() to check whether two strings are anagram of each
other or not using built-in functionand are Anagram2() to check the anagram without using built-
in function. (10)
14.a.i)Define Dictionary in Python. Do the following operations on dictionaries.(10)
i) Initialize two dictionaries and create a new dictionary with key value pairs.
ii) Compare the two dictionaries with master key and print missing keys.
iii)Find keys that are in first and not in second dictionary.
iv) Find same keys in two dictionaries.
v)Merge two dictionaries and create a new dictionary using a single expression.
ii)What is list comprehension in python? Explain with example. (6)
OR
b.i)What is tuple in python? How does it differ from list?(8)
ii)Write a python program t sort n numbers using merge sort.(8)
15.a.i)What are Exceptions? Explain the method to handle them with example.(8)
ii) Write a python program to count the number of words in a text file.(8)
b.i)How to merge multiple files into a new file using python.(6)
ii)What are modules in python? How will you import them? Explain the concept by
creating and importing a module. (10)

249
Problem Solving and Python Programming 2020

REFERENCES
TEXT BOOKS:
1. Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist’’, 2nd edition,
Updated for Python 3, Shroff/O’Reilly Publishers, 2016 (http://greenteapress.com/wp/think-
python/)
2. Guido van Rossum and Fred L. Drake Jr, “An Introduction to Python – Revised and
updated for Python 3.2, Network Theory Ltd., 2011.
REFERENCES:
1. Charles Dierbach, “Introduction to Computer Science using Python: A Computational
Problem-Solving Focus, Wiley India Edition, 2013.
2. John V Guttag, “Introduction to Computation and Programming Using Python’’, Revised
and expanded Edition, MIT Press , 2013
3. Kenneth A. Lambert, “Fundamentals of Python: First Programs”, CENGAGE Learning,
2012.
4. Paul Gries, Jennifer Campbell and Jason Montojo, “Practical Programming: An Introduction
to Computer Science using Python 3”, Second edition, Pragmatic Programmers,LLC,2013.
5. Robert Sedgewick, Kevin Wayne, Robert Dondero, “Introduction to Programming in
Python: An Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd., 2016.
6. Timothy A. Budd, “Exploring Python”, Mc-Graw Hill Education (India) Private Ltd.,, 2015.

250

You might also like