You are on page 1of 133

GE8151 - Problem Solving and Python Programming

Bhaskar V
Premkumar P

July 30, 2019

Unit I
Short Questions

Algorithms, building blocks of algorithms

1. Give an informal definition about an algorithm.


An algorithm is any well-defined computational function that takes
some value, or set of values, as input and produces some value,
or set of values, as output. An algorithm is thus a sequence of
computational steps that transform the input into the output.
2. Point out an example problem solved by computer algorithm.
The Human Genome Project has made great progress toward the
goals of identifying all the 100,000 genes in human DNA, determining
the sequences of the 3 billion chemical base pairs that make up human
DNA, storing this information in databases, and developing tools for
data analysis. Each of these steps requires sophisticated algorithms.
The Internet enables people all around the world to quickly access
and retrieve large amounts of information. With the aid of clever
algorithms, sites on the Internet are able to manage and manipulate
this large volume of data.
3. Give an example of a sorting problem.
Input: A sequence of n numbers a1, . . . , an Output: A permutation
or reordering < a01, . . . , a0n > such that for every i < j, a0i ≤ a0j .
1
4. Name the three steps in solving a problem.
(i) Understand the problem (ii) Find the connection between the
data and the unknown – devise a plan(iii) carry out the plan and
examine the solution obtained.(iv) look back – check if there are
more approaches.
5. State the purpose of problem solving through computers.
Computers are very fast in solving problems. The Computer calculates
with great accuracy. A Computer produces results without any error.
A repetitive calculation is performed with the same accuracy for any
number of times in a Computer. That is why Computers are used in
solving problems.
6. List the characteristics of a good algorithm.
The properties of Algorithm are: 1) There must be no ambiguity in
any instruction.2) There should not be any uncertainty about which
instruction is to be executed next. 3) The algorithm should conclude
after a finite number of steps. An algorithm cannot be open-ended.
The algorithm must be general enough to deal with any contingency.

Instructions/statements, state, control flow, functions, notation, pseudocode,


flowchart, programming language.

7. Define the term ‘pseudo-code’


Pseudocode is not the actual name but it models and may even
look like programming code. It is the generic way of describing an
algorithm without using any programming language related notations.
Or, more simply it is the outline of the program, written in a form
that can be easily converted into real programming statements.
8. Mention the need for pseudocodes.
For developing an effective algorithm, flowcharts and pseudocodes are
used by programmers. They are further expressed in programming
languages to develop computer programs.

2
9. What is meant by computational complexity of an algorithm?
It is the execution time of the algorithm in terms of its input parameters.
10. Give the advantages and limitations of flowchart.
Advantages: it makes the logic clear and visual. It communicates
the interconnection of the logical system. The problem can be well
analysed. Useful for coding the problem. Testing and debugging is
easily done. Flowcharts are good programming documentation for
future reference. Disadvantages: it is complicated. It is costly and
difficult to modify in future and no updates are easy to do.
11. Give the advantages and limitations of pseudocode.
Advantages: it is language independent. It is easier to develop
program from pseudocode than from flowchart. It is very compact
than a flowchart. Limitations: Pseudocode may vary for different
programming languages thus it is implementation specific so not
every developer can understand.
12. Name the three basic program control structures.
Sequence, selection and repetition.
13. Write the algorithm for finding the sum of any two numbers
Let the two numbers be A and B and let their sum be equal to C.
Then, the desired algorithm is given as follows:
1. START
2. PRINT “ENTER ANY TWO NUMBERS”
3. INPUT A,B
4. C ← A + B
5. print C
6. STOP
14. Write an algorithm to check whether the given number is
odd or even.
Let the number to be checked be represented by N. The number
N is divided by 2 to give an integer quotient, denoted by Q. If
3
the remainder, designated as R, is zero, N is even; otherwise N
is odd. This logic has been applied in the following algorithm:

1. START
2. print “ENTER THE NUMBER”
3. INPUT N
4. Q ← N/2 (INTEGER DIVISION)
5. R←N −Q×2
6. if R = 0 then
7. print “N IS EVEN”
8. if R = 1 then
9. print “N IS ODD”
10. STOP
15. Write an algorithm to print the largest of 3 numbers.
Let the three numbers be represented by A, B, and C. There can be
three ways of solving the problem. The three algorithms, with some
differences, are given below:
1. START
2. print “Enter Three Numbers”
3. INPUT A, B, C
4. if A > B then
5. if A > C then
6. print A
7. else
8. if C > B then
9. print C
10. else
11. print B
12. else
13. if B > C then
14. print B
15. else

4
16. print C
17. STOP
The following algorithm uses ’AND’ operator to simplify the logic of
execution:
1. START
2. print "ENTER THE THREE NUMBERS A, B, C"
3. READ A, B, C
4. if A > B and A > C then
5. print A
6. if B > C and C > A then
7. print B
8. else
9. print C
10. STOP
The following algorithm uses a variable MAX to store the largest
number.
1. START
2. print “ENTER THREE NUMBERS”
3. INPUT A, B, C
4. M AX ← A
5. if B > M AX then
6. M AX ← B
7. if C > M AX then
8. M AX ← C
9. print M AX
10. STOP
16. List few of the flow-chart symbols:
See Figure 1
17. Mention the guidelines for drawing flow-charts.
• In drawing a proper flowchart, all necessary requirements should
be listed out in a logical order.
5
Start

Input Process

Decision Output

Stop

Figure 1: Flow-Chart Symbols

• There should be a logical start and stop to the flowchart.


• The flowchart should be clear, neat, and easy to follow. There
should be no ambiguity in understanding the flowchart.
• The usual direction of the flow of a procedure or system is from
left to right or top to bottom.
• Only one flow line should emerge from a process symbol see
Figure 2.

Process1 Process2

No Decision1 Yes

Figure 2: Flow-Chart Rules

18. Mention the advantages and limitations of using flow-charts


Advantages of using flowcharts

6
• Communication Flowcharts are a better way of communicating
the logic of a system to all concerned.
• Effective analysis With the help of flowcharts, problems can be
analysed more effectively.
• Proper documentation Program flowcharts serve as a good program
documentation needed for various purposes.
• Efficient coding Flowcharts act as a guide or blueprint during the
systems analysis and program development phase.
• Proper debugging Flowcharts help in the debugging process.
• Efficient program maintenance The maintenance of an operating
program become easy with the help of a flowchart.
Limitations of using flowcharts
• Complex logic Sometimes, the program logic is quite complicated.
In such a case, a flowchart becomes complex and clumsy.
• Alterations and modifications If alterations are required, the flowchart
may need to be redrawn completely.
• Reproduction Since the flowchart symbols cannot be typed in, the
reproduction of a flowchart becomes a problem.
• The essentials of what has to be done can easily be lost in the
technical details of how it is to be done.
19. Draw a flowchart to find the sum of the first 50 natural
numbers
See Figure: 3
20. Draw a flowchart to find the largest of three numbers A, B,
and C.
See Figure: 4
21. Give comment on pseudocode and actual/real code
What separates pseudocode from “real” code is that in pseudocode,
we employ whatever expressive method is most clear and concise
to specify a given algorithm. Sometimes, the clearest method is
7
Start N ←N +1

SUM=0 SU M ← SU M + 1

N=0

IS N > 50?
No

Yes

PRINT SU M

STOP

Figure 3: Flow-Chart for Sum of 50 natural numbers

English, so we may not be surprised if we come across an English


phrase or sentence embedded within a section of “real” code. Another
difference between pseudocode and real code is that pseudocode is
not typically concerned with issues of software engineering. Issues of
data abstraction, modularity, and error handling are often ignored in
order to convey the essence of the algorithm more concisely.

Unit I
Big Questions

Algorithms, building blocks of algorithms

1. List and explain the steps that a programmer follows in


writing a program.
Problem Analysis — The programmer first understands the problem
to be solved. The programmer determines the various ways in which
the problem can be solved, and decides upon a single solution which

8
Start

READ A, B, C

Yes
Is B > C? Is A > B? Is A > C?
Yes No YES

No No

PRINT B PRINT C PRINT A

STOP

Figure 4: Flow-Chart for Largest of 3 numbers

will be followed to solve the problem.


Program Design — The selected solution is represented in a form,
so that it can be coded. This requires three steps —
• An algorithm is written, which is an English-like explanation of
the solution.
• A flowchart is drawn, which is a diagrammatic representation of
the solution. The solution is represented diagrammatically, for
easy understanding and clarity.
• A pseudo code is written for the selected solution. Pseudo code
uses the structured programming constructs. The pseudo code
becomes an input to the next phase.
Program Development
• The computer programming languages are of different kinds –
low-level languages, and high- level languages like C, C++, Python
9
and Java. The pseudo code is coded using a suitable programming
language.
• The coded pseudo code or program is compiled for any syntax
errors. Syntax errors arise due to the incorrect use of programming
language or due to the grammatical errors with respect to the
programming language used. During compilation, the syntax
errors, if any, are removed.
• The successfully compiled program is now ready for execution.
• The executed program generates the output result, which may be
correct or incorrect. The program is tested with various inputs, to
see that it generates the desired results. If incorrect results are
displayed, then the program has semantic error (logical error).
The semantic errors are removed from the program to get the
correct results.
• The successfully tested program is ready for use and is installed
on the user’s machine.
Program Documentation and Maintenance — The program
is properly documented so that, later on, anyone can use it and
understand its working. Any changes made to the program, after
installation, forms part of the maintenance of programs. The program
may require updating, fixing errors etc. during the maintenance
phase.
2. What are the three tools the programmer uses to develop a
program solution?
i) flow-chart ii) pseudo-code iii) algorithm(explain each as above)
3. Given two variables a and b exchange the values assigned to
them
Consider the variables are assigned values as outlined below:
Starting Configuration:
a : 123 b : 456
This means that memory cell or variable a contains the value 123
10
and memory cell or variable b contains the value 456. Our task is to
replace the contents of a with 456, and the contents of b with 123.
In other words we want to end up with the configuration below:
Target Configuration:
a : 456 b : 123
To exchange the value of a variable, we can use the assignment
operator. Because we want a to assume the value currently belonging
to b, and b the value belonging to a we could perhaps make the
exchange with the following assignments:
a←b (1)
b←a (2)
where "←" is the assignment operator. In (1) "←" causes the value
stored in memory cell b to be copied into memory cell a.
Let us work through these two steps to make sure they have the
desired effect. We started out with the configuration:
a : 123 b : 456
then after execution of the assignment a ← b we have
a : 456 b : 456
The assignment (1) has changed the value of a but has left the value
of b untouched. Checking with our target configuration we see that
a has assumed the value 456 as required. So far so good! We must
also check on b. When the assignment step (2) i.e. b ← a is made
after executing step (1) we end up with:
a : 456 b : 456
In executing step (2) a is not changed while b takes on the value
that currently belongs to a. The configuration that we have ended
up with does not represent the solution we are seeking. The problem
arises because in making the assignment:
a←b
we have lost the value that originally belonged to a (i.e. 123 has been
lost). It is this value that we want b to finally assume. Our problem
must therefore be stated more carefully as:

11
new value of a ← old value of b;
new value of b ← old value of a
What we have done with our present proposal is to make the assignment
new value of b ← new value of a.
In other words when we execute step (2) we are not using the value a,
that will make things work correctly—because a has already changed.
To solve this exchange problem, we need to find a way of not destroying
"the old value of a" when we make the assignment a ← b
A way to do this is to introduce a temporary variable t and copy the
original value of a into this variable before executing step (1). The
steps to do this are:

t ← a; (3)
a ← b; (4)
After these two steps we have
a : 456 t : 123 b : 456
Now we have to copy down the value of t to b so that we will be able
to achieve exchanging the values between a and b.
b ← t; (5)

4. Discuss the three basic program control structures with


suitable examples.
Sequence Control Structure: As the name implies, in a sequence
structure, the instructions to be computed simply follow one another
in a logical progression. This structure is denoted by writing one
action after another, each action on a line by itself, and all actions
aligned with the logical indent. The actions are performed in the
same sequence (top to bottom) in which they are written. Typical
sequence operations consist of the process and I/ O steps. Figure 5
illustrates a simple sequence:
Selection Structure: A selection structure allows the program to
make a choice between two alternate paths, whether it is true or false.
The first statement of a selection structure is a conditional statement.
12
ACTION 1

ACTION 2

ACTION n

Figure 5: Flow-Chart for Sequence Construct

Test True Test False


Expression False Expression

True Statement1 Statement2

Statement

(a) if expression branching (b) if expression . . . else. . . branching

Figure 6: Branching Process

Once the sequence of steps in the selected path has been carried out,
the paths are rejoined and then the next instruction is carried out.
Thus, the selection structure has only a single entry and a single exit.
In the example given in Figure 6a, we have a Test expression which
is evaluated. In the selection process, if the expression is true then
the statement is executed if the expression is false, the statement
is bypassed Figure 6a. In Figure 6b, if the Test expression evaluates
to True, then, statement1 is executed otherwise statement2 will
be executed

13
False
Condition
Repeated Task

True
False
Condition Repeated Task

True
(a) repeat. . . until – post-test loop (b) while – pre-test loop

Figure 7: Repetition Process

Repetition: Repetition or loop pattern causes an interruption in


the normal sequence of processing (Figure 7) It directs the system
to loop back to a previous statement in the program, repeating the
same sequence over and over again, usually with new data. When a
sequence of statements is repeated against a condition, it is said to
be in a loop. Using looping, the programmer avoids writing the same
set of instructions again and again. The looping process can either
be one time or multiple times until the desired output is obtained(or,
the given condition is satisfied) within a single program.
In the Figure 7 we have two types of repetition or looping – the
first one Figure 7a is a post test loop(also known as repeat . . . until
loop) and the second one Figure 7b is a pre test loop(also known as
a while loop).
The following example,(Figure 8), prints the first 10 natural numbers.
Notice that at the beginning, the value of COU N T variable is initialized
to zero. After that, COU N T is incremented by one and the value is
printed. If the value of COU N T is less than 10 (which represents the
count of numbers to be displayed) then the same process is repeated.
At the conclusion of each iteration, the condition is evaluated, and
the loop repeats until the condition becomes true. The loop terminates
when the condition becomes false.
14
Start

COU N T ← 0

COU N T ← COU N T + 1

Print COU N T

Is COU N T < 10?


Yes

No
Stop

Figure 8: Flow-Chart to Print first 10 numbers

5. Give the algorithm for insertion sort.


Insertion sort is an efficient algorithm for sorting a small number of
elements. Insertion sort works the way many people sort a hand of
cards. We start with an empty left hand and the cards face down
on the table. We then remove one card at a time from the table and
insert it into the correct position in the left hand. To find the correct

Figure 9: Insertion Sort

position for a card, we compare it with each of the cards already in


the hand, from right to left, as illustrated in Figure 9 At all times, the
15
cards held in the left hand are sorted, and these cards were originally
the top cards of the pile the table. We present our pseudo-code for
insertion sort as a procedure called INSERTION-SORT, which takes
as a parameter array A[1..n] containing a sequence of length n that
is to be sorted. (In the code, the number n of elements in A is
denoted by A.length.) The algorithm sorts the input numbers in
place: it rearranges the numbers within the array A, with at most
a constant number of them stored outside the array at any time.
The input array A contains the sorted output sequence when the
INSERTION-SORT procedure is finished.

Figure 10: The operation of INSERTION-SORT on the array A = h5, 2, 4, 6, 1, 3i.


Array indices appear above the rectangles, and values stored in the array positions
appear within the rectangles. (a)–(e) The iterations of the for loop of lines 1–8. In
each iteration, the black rectangle holds the key taken from A[j], which is compared
with the values in shaded rectangles to its left in the test of line 5. Shaded arrows
show array values moved one position to the right in line 8, and black arrows indicate
where the key moves to in line 8. (f) The final sorted array.

Figure 10 shows how this algorithm works for A = h5, 2, 4, 6, 1, 3i.


The index j indicates the “current card” being inserted into the hand.
At the beginning of each iteration of the for loop, which is indexed
by j, the subarray consisting of elements A[1..j − 1] constitutes
the currently sorted hand, and the remaining subarray A[j + 1..n]
corresponds to the pile of cards still on the table. In fact, elements
A[1..j − 1] are the elements originally in positions 1 through j − 1,
but now in sorted order. We state these properties of A[1..j − 1]
formally as a loop invariant.
We see that the key is the card which is to be inserted. In the sub-loop

16
1. for j = 2 to A.length do
2. key = A[j]
3. //Insert A[j] into the sorted sequence A[1..j − 1].
4. i=j−1
5. while i > 0 and A[i] > key do
6. A[i + 1] = A[i]
7. i=i−1
8. A[i + 1] = key
Algorithm 1: Insertion-Sort

we are checking first whether the key is smaller than the card at the
ith position. If so, then shift it to the right and we terminate the
inner loop as soon as we come across a card, that is smaller than key
and thereby insert the card one position above the smaller card also
if the smallest card on hand happens to be larger than the key and
will obviously be inserted into the lowest position.
At the start of each iteration of the for loop of lines 1–8, the subarray
A[1..j − 1] consists of the elements originally in A[1..j − 1], but in
sorted order.
We use loop invariants to help us understand why an algorithm is
correct. We must show three things about a loop invariant.
Initialization: It is true prior to the first iteration of the loop.
Maintenance: If it is true before an iteration of the loop, it remains
true before the next iteration.
Termination: When the loop terminates, the invariant gives us a
useful property that helps show that the algorithm is correct.
When the first two properties hold, the loop invariant is true prior to
every iteration of the loop. (Of course, we are free to use established
facts other than the loop invariant itself to prove that the loop
invariant remains true before each iteration.) Note the similarity
to mathematical induction, where to prove that a property holds,
we prove a base case and an inductive step. Here, showing that
the invariant holds before the first iteration corresponds to the base

17
case, and showing that the invariant holds from iteration to iteration
corresponds to the inductive step. The third property is perhaps
the most important one, since we are using the loop invariant to
show correctness. Typically, we use the loop invariant along with
the condition that caused the loop to terminate. The termination
property differs from how we usually use mathematical induction,
in which we apply the inductive step infinitely; here, we stop the
“induction” when the loop terminates.
6. Develop an algorithm and flowchart to find the minimum
and maximum in a list of numbers.
In this algorithm let us use the function length(list) see Algorithm
2 which will return the length of the argument list. Let us also use
two variables called min and max which will hold the minimum and
maximum of the list under consideration. The while loop can be
used to traverse over the list in checking the values of the variables
in and update the min and max variables as and when we come across
a smaller and larger values. The index variable i which is initialised
as 0 before the entry into the while loop will be incremented by 1
each step as the loop advances in the list. The flowchart is hown in
Figure 11
7. Write an algorithm to insert a card into a list of sorted
cards.
Let us assume that we hold the sorted cards in the left hand and the
card to e inserted is on the table. This can be shown as below:
x
Sorted cards j th
When we want to insert the card x into the sorted cards, then we
must know which position among the sorted cards, it can be inserted.
Let the number of sorted cards be j then if we assume the first array
position as 0 and then the position of the last card in the sorted cardsl
be j − 1; If the card in hand happens to be smaller than the card at
the (j − 1)th position, we would need to shift it to the j th position

18
1. READ a list of numbers
2. min ← list[0]
3. max ← list[0]
4. i←0
5. length ← lengthof list
6. while i < length do
7. if min > list[i] then
8. min ← list[i]
9. if max < list[i] then
10. max ← list[i]
11. i←i+1
12. print min, max
Algorithm 2: Find maximum and minimum of a list of numbers

etc. to enable it to be inserted. The following algorithm segment will


achieve this task:
while j > 0 and x < A[j − 1] do
A[j] = A[j − 1]
j =j−1
A[j] = x
In the above algorithm, if the value of x happens to be greater than
A[j − 1], then x will get into the position A[j]. Otherwise we will
be shifting the higher valued cards to the right of the array by one
position in each iteration and finally insert the card into the position
j.
8. Draw the flow-chart and write an algorithm for printing the
factorial of the given number n that is
n! = n × (n − 1) × (n − 2) × . . . × 2 × 1.
First of all we read the value of n. While calculating the factorial of
a number, there are two variables involved. 1) The i value and 2)
the f act value. The i value is initially set to 0 and f act is set to 1.
Since
19
Start

READ the Is
No
list of numbers i < length?

Yes
min ← list[0]
max ← list[0]

Is
Yes min > list[i]
length ← length
of list

min ← list[i]

No
i←0

Yes Is
max < list[i]

max ← list[i]

No

PRINT min, max

STOP

Figure 11: Flow-Chart for Minimum and Maximum of a list of numbers

n! = n × (n − 1) × (n − 2) × . . . × 3 × 2 × 1.
Since, 0! = 1, when initially, n = 0, the condition i = n becomes

20
immediately True and our program doesn’t enter the loop at all. If
n > 0, the looping will take place at least once. In every iteration, i
is incremented by 1 and it gets multiplied with f act and the result is
assigned to f act itself. Thus the loop will terminate when i = n and
at that time, the f act value will be the factorial of n. The algorithm
3 and flow-chart for computing factorial is shown in Figure: 12

1. READ n // n ≤ 0
2. i←0
3. f act ← 1
4. while i < n do
5. i←i+1
6. f act ← i × f act
7. print f act
Algorithm 3: Factorial Algorithm(Iterative)

9. Describe the characteristics of programming languages.


computer needs to be instructed using computer programs to perform
all its tasks; for this, programs are written in special computer languages.
A natural language is not used to instruct the computer even though
a programming language consists of a set of characters, symbols, and
usage rules that allow the user to communicate with computers, just
as in natural languages. Programming languages can be divided into
three major categories:
Machine Language: It is the native language of computers. It uses
only ‘0’ s and ‘1’ s to represent data and the instructions.
Assembly Language: It corresponds to symbolic instructions and
executable machine codes and was created to use letters instead of
‘0’ s and ‘1’ s to run a machine.
High-level Language: These languages are written using a set of
words and symbols following some rules similar to a natural language,
such as English. The programs written in high-level languages are

21
Start

READn

i←0
f act ← 1

Is i = n? Yes

No
i←i+1
Print f act
f act ← f act × i

Stop

Figure 12: Flow-Chart to calculate Factorial n

known as source programs and these programs are converted into


machine-readable form by using compilers or interpreters.
10. Write a recursive algorithm to solve towers of Hanoi problem.
Problem Description
The Towers of Hanoi problem is the task of moving a collection of
N stone disks from one pillar, designated as pillar A to another,
designated as C in the Figure 13a. A relative ordering of the disks
on pillar A had to be maintained as they were moved to pillar C.
That is, as illustrated Figure: 13, the disks were to be stacked in
largest to smallest fashion beginning from the bottom. Additionally,
the following rules were to be observed in moving disks:
• Only one disk could be moved at a time.
• No larger disk could ever reside on a pillar on top of a smaller
disk

22
• A third pillar B to store one or more disks while they were being
moved from their original source A to their destination C
Consider the following recursive solution to this problem:
1. If N = 1, merely move the disk from A to C.
2. If N = 2, move 1st disk from A to B. Then move 2nd disk from
A to C. Then move 1st disk from B to C.
3. If N = 3, call upon the technique already established in (2) to
move the first 2 disks from A to B using C as an intermediate.
Then move the 3rd disk from A to C. Then use the technique in
(2) to move 2 disks from B to C using A as an intermediate.
4. For general N , use the technique already established to move
N − 1 disks from A to B using C as an intermediate. Then move
one disk from A to C. Then again use the technique already
established to move N − 1 disks from B to C using A as an
intermediate.
N − 1 disks
...
...

N disks

A B C A B C
(a) Initial State (b) Second State if N > 3

Figure 13: Towers of Hanoi

Notice that the technique described here calls upon itself, but switches
the order of parameters in so doing. This can be formalized in the
following pseudo code:
FUNCTION HANOI(N, SOURCE, DESTINATION, INTERMEDIATE)
VAR L1,L2:LABEL
VAR N: INTEGER
VAR SOURCE, DESTINATION, INTERMEDIATE: CHARACTER

23
N − 1 disks

...
N disks

A B C A B C
(a) Third State (b) Goal State

Figure 14: Towers of Hanoi

IF N = 1 THEN
WRITE "MOVE DISK FROM" SOURCE, "TO" DESTINATION
RETURN
ENDIF
CALL HANOI (N-1, SOURCE, INTERMEDIATE, DESTINATION)
(*In all recursive call HANOI works with value N less 1*)
L1: WRITE "MOVE DISK FROM" SOURCE, "TO", DESTINATION
CALL HANOI(N-1, INTERMEDIATE, DESTINATION, SOURCE)
L2: RETURN
END HANOI
Because we have a CALL to HANOI within the function HANOI,
this represents a recursive CALL. Although such a function is easy
to write in pseudo-code, it is somewhat more difficult to understand
thoroughly
The key to understanding the function is to be aware of what a
compiler must do when the recursive call is made.The difficulty with
handling recursion is that, because we call a function from within
the function, eventually a return will be made to that same function.
However, because the call also involves changing the values of the
function’s parameters the old values of the parameters will have been
destroyed upon return unless they preserved before the recursive call.
The best way of preserving them is to stack them with the return
address. Thus, a recursive call involves stacking not only a return
address but also values of all parameters essential to the current

24
state of the function. In this sense, it is crucial that all functions
which are recursively called receive actual working copies of their
parameters rather than merely the memory addresses of the calling
program’s variables. That is, recursively called functions should
receive parameters by value, not by reference. To illustrate, we will
trace through the actions taken when a call of the form
CALL HANOI(3,"A","C","B")
is initiated. Figure 13a and 14b (here "A" is the source, "C" is the
destination and N = 3)
1. N is not 1 so the condition in the IF statement is false.
2. CALL HANOI (N −1, SOURCE, INTERMEDIATE, DESTINATION)
is encountered with A, B, and C as Ist, 2nd, and 3rd arguments.
Because this represents a recursive call, some stacking must be
done:
B (intermediate)
C (destination)
A (source)
L1 3 (N)
Return address stack Parameter stack

3. Reenter HANOI. Notice that as we enter this time, the function’s


view of the parameters is N = 2, SOURCE=A,DESTINATION=B,
INTERMEDIATE=C. Because N is not 1, the condition in the
IF statement is false.
4. CALL HANOI(N-1, SOURCE,INTERMEDIATE,DESTINATION)
is encountered. Because this is a recursive call, stacking occurs:
C (intermediate)
B (destination)
A (source)
2 (N)
B (intermediate)
C (destination)
L1 A (source)
L1 3 (N)
Return address stack Parameter stack

25
5. We reenter HANOI with N = 1, SOURCE=A, DESTINATION=C
and INTERMEDIATE=B. Because N = 1, the condition in the
IF statement is true.
6. Hence:
MOVE DISK FROM A TO C (1)
is output and a RETURN triggers a popping of a return address(L1)
and four parameters(N = 2, SOURCE=A,DESTINATION=B,
and INTERMEDIATE=C).
B (intermediate)
C (destination)
A (source)
L1 3 (N)
Return address stack Parameter stack

7. Because the return address popped was L1:

MOVE DISK FROM A TO B (2)


is output and:
CALL HANOI(N − 1,INTERMEDIATE,DESTINATION,SOURCE
is encountered with N = 2, SOURCE=A,DESTINATION=B
and INTERMEDIATE=C.
8. The call pushes a return address and 4 parameters onto the
stacks.
C (intermediate)
B (destination)
A (source)
2 (N)
B (intermediate)
C (destination)
L2 A (source)
L1 3 (N)
Return address stack Parameter stack

9. We reenter HANOI , this time with N = 1, SOURCE = C,


DESTINATION = B, INTERMEDIATE = 1.

26
10. Because N = 1, the IF statement generates the output:

Move DISK FROM C TO B (3)


and a RETURN.
11. The RETURN pops values from both stacks and we return to L2
with N = 2, SOURCE =A, DESTINATION = B, INTERMEDIATE
= C.
12. But L2 is a RETURN statement itself, so both stacks are popped
again and we return to L1 with N = 3, SOURCE = A, DESTINATION
= C, INTERMEDIATE = B, and both stacks temporarily empty.
13. Line L1 triggers the output:

MOVE DISK FROM A TO C (4)


and we are immediately at another call:
CALL HANOI (N − 1, INTERMEDIATE, DESTINATION, SOURCE)
Hence the temporary empty status of the stack is changed to
B (intermediate)
C (destination)
A (source)
L2 3 (N)
Return address stack Parameter stack

14. Reenter HANOI with N = 2, SOURCE = B, DESTINATION=C,


INTERMEDIATE=A. Because N is not 1, another call:
CALL HANOI(N − 1,SOURCE,INTERMEDIATE,DESTINATION)
is executed and more values are stacked:
A (intermediate)
C (destination)
B (source)
2 (N)
B (intermediate)
C (destination)
L1 A (source)
L2 3 (N)
Return address stack Parameter stack

27
15. Reenter HANOI with N = 1, SOURCE = B, DESTINATION=A,
INTERMEDIATE=C. Because N = 1, output:

MOVE DISK FROM B TO A (5)


and RETURN.
16. The return prompts the popping of both stacks. The return
address popped is L1 with parameters N = 2, SOURCE=B,
DESTINATION=C,INTERMEDIATE=A, statement L1 causes
output:

MOVE DISK FROM B TO C (6)


with the stack left at:
B (intermediate)
C (destination)
A (source)
L2 3 (N)
Return address stack Parameter stack

17. The output from L1 is followed by:


CALL HANOI(N − 1,INTERMEDIATE,DESTINATION,SOURCE)
so pushed onto the stacks are:
A (intermediate)
C (destination)
B (source)
2 (N)
B (intermediate)
C (destination)
L2 A (source)
L2 3 (N)
Return address stack Parameter stack

18. Reenter(for the last time) HANOI with N = 1, SOURCE =


A,DESTINATION = C, INTERMEDIATE = C. Because N = 1,
output:

MOVE DISK FROM A TO C (7)


28
and RETURN
19. But now the RETURN pops RETURN address L2 from the stack,
so return to L2 with N = 2, SOURCE=B,DESTINATION=C,
INTERMEDIATE=A:
B (intermediate)
C (destination)
A (source)
L2 3 (N)
Return address stack Parameter stack

20. L2 is another RETURN, so pop the stacks again. Return address


popped is L2, the same RETURN statement. But this time
the RETURN will transfer control back to the original calling
function and
WE ARE DONE!

Unit II
Short Questions

DATA, EXPRESSIONS AND STATEMENTS

Python Interpreter and interactive mode

1. Give a brief description about Python?


Python is a high-level, interpreted, interactive and object-oriented
language. Python is designed to be highly readable. It uses English
keywords frequently whereas other languages use punctuation, and
it has fewer syntactical construction than other languages.
2. Mention the six main reasons why people choose to use
Python.
Software quality, developer productivity, program portability, support
libraries, component integration, and simple enjoyment. Of these,
the quality and productivity themes seem to be the main reasons
that people choose to use Python.

29
3. Name some of the features of python.
Following are some of the salient features of python;
• It supports functional and structured programming methods as
well as OOP. ıtem It can be used as a scripting language or can
be compiled to byte-code for building large applications.
• It provides very high-level dynamic data types and supports dynamic
type checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, ActiveX, CORBA, and
Java.
4. Mention the use of IDLE tool?
The IDLE tool offers a more efficient platform to write code and work
interactively with Python. We can access IDLE on the same folder
or the command line icon or on the start menu.
5. Explain the steps to exit from Python?
To exit from Python, you can type any of these commands:
• quit()
• exit()
Control-Z then press enter key.
6. Mention about the Python interpreter?
The Python interpreter is a program that runs the Python programs
we write.
7. Define a source code. What is byte code?
Source code is the statements we write for our program—it consists
of text in text files that normally end with a .py extension. Byte
code is the lower-level form of our program after Python compiles it.
Python automatically stores byte code in files with a .pyc extension.

30
8. Explain briefly about the Python Virtual Machine(PVM)?
The PVM is the Python Virtual Machine – the runtime engine of
Python that interprets our compiled byte code.
9. Mention the two ways of Using Python Interpreter?
Interactive mode - Interactive mode is a command line shell which
gives immediate feedback for each statement, while running previously
fed statements in active memory.
Script mode - A script mode can store code in a file and it uses the
interpreter to execute the contents of file.
10. Explain the steps involved to run a script from within IDLE?
Within the text edit window of the file we wish to run, we must
select the window’s Run→Run Module menu option. This runs the
window’s source code as a top-level script file and displays its output
back in the interactive Python shell window.

Values and Types

11. Define data types.


Data type is a set of values and allowable operations on those values.
Data types allow programming languages to organize different kinds
of data.
12. Name the four types of scalar objects Python has.
int Any integer. float Floating point number (64 bit precision)
complex Numbers with an optional imaginary component. bool
True, False str A sequence of characters (can contain unicode characters).
13. Name four of Python’s core data types.
Numbers, strings, lists, dictionaries, tuples, files, andsets are generally
considered to be the core object (data) types. Types, None , and
Booleans are sometimes classified this way as well. There are multiple
number types (integer, floating point, complex, fraction, and decimal)

31
and multiple string types (simple strings and Unicode strings in
Python 2.X, and text strings and byte strings in Python 3.X).

Variables and Expressions

14. List out the rules used for naming a variable in python.
• Variable names can only contain upper case (A-Z), lower case
(a-z) letters digits (0-9) and underscore characters.
• Variable names are case sensitive
• Numbers are allowed, but they should not be used at the beginning
of the variable name.
• Camel case notation or underscores can be used. Camel case is
the practice of writing compound words with mixed casing.
• No special symbols other than underscore are allowed.
• Reserved keywords cannot be used as a variable name
15. Describe the way to assign a value to a variable in python.
The equal sign (=) is used to assign values to variables. The operand
to the left of = operator is the name of the variable and the operand
to the right of = operator is the value stored in that variable. Syntax:
<variable name> = <value>
16. Define Keywords.
Keywords or reserved words are special commands that compiler/interpreter
understands and these reserve words cannot be used as a const variable,
or any other identifier names. There are 33 keywords.
17. Define Identifiers.
An identifier is a name used to identify a variable, function, class,
module or any other object. It helps differentiating one entity from
another.
18. Explain about “Immutable”, and mention the three Python’s
core types that are considered immutable.
32
An “immutable” object is an object that cannot be changed after
it is created. Numbers, strings, and tuples in Python fall into this
category. While we cannot change an immutable object in place, we
can always make a new one by running an expression. Byte arrays
in recent Pythons offer mutability for text, but they are not normal
strings, and only apply directly to text if it’s a simple 8-bit kind (e.g.,
ASCII).
19. Define multiline statement in Python.
A multiple line expression is a single statement by wrapping the lines
inside braces {},square brackets [ ] and parentheses ( ).
20. Write the syntax for the Python output function.
print("<expression>")
#multiple expressions
print("<expression>,<expression>")
print("<expression>",<variable name>)

21. Define raw_input() with syntax


The raw_input([prompt] ) function reads one line from standard
input and returns it as a string(removing the trailing new line).
Syntax: variable_name = raw_input("<prompt: Input Statement>
22. Describe how to import modules in Python?
A module is a built-in file containing python definitions and statements
with the .py extension, which implement a set of functions. Modules
are imported from other modules using the import command.
Syntax: import <modulename>
Example: import math

Precedence of Operators and Comments

23. Identify the method to write Comments in python.


Comments are used by programmers for better understanding of a
program Comments are very important while writing a Program. It
33
Table 1: Bitwise Operators
Operator Description Example Result
x=5(510 = 01012)
& (Binary AND) x&3 1
| (Binary OR) x|3 7
ˆ (Binary XOR) xˆ 3 6
˜ (Binary Ones Complement) ˜x -6
<< (Binary Left Shift) x<<2 20

describes what the source code has done. In Python, we use the
hash (#) symbol to start writing a comment Alternatively, use triple
single (''') or triple double quotes (""") at the start and end of a
multiple-line comment. Python interpreter ignores comment.
24. Define Operators and list its type.
An operator is a symbol that represents an operation performed
on one Or more operands. An operand is a quantity on which an
operation is performed Operators that take one operand are called
unary operators. A binary operator operates on two operands. Python
uses different operators. They are:
1. Arithmetic Operators
2. Relational or Comparison Operators
3. Assignment Operators
4. Bit wise Operators Logical Operators
5. Membership Operators
6. Identity Operators
25. Outline in a few words about bitwise operators in Python?
Bitwise operations are operations that directly manipulate bits. It
performs bit by bit operations. It returns binary coded output(Table:1).

26. Compute the value of the expression 2 * (3 + 4) in Python?


34
The value will be 14 , the result of 2 * 7, because the parentheses
force the addition to happen before the multiplication.
27. Compute the value of the expression 2 * 3 + 4 in Python?
The value will be 10 , the result of 6 + 4. Python’s operator
precedence rules are applied in the absence of parentheses, and multiplication
has higher precedence than (i.e., happens before) addition.
28. Discuss the use of //, ** operator with suitable example.
The floor division operator, //, divides two numbers and rounds
down to an integer. For example, suppose the run time of a movie
is 111 minutes. We might want to know how long that is in hours.
Conventional division returns a floating-point number.

>>> hours = 111 / 60


>>> hours
1.85
>>>

Floor division returns the integer number of hours, dropping the


fraction part

>>> hours = 111 // 60


>>> hours
1

The operator ** performs exponentiation; that is, it raises a number


to a power:

>>> answer = 5**2 + 3


>>> answer
28
>>>

29. Define Membership operator.

35
Membership operators are used to test whether a value (variable) is
found in a sequence like string, list, tuple, set and dictionary. There
are two membership operators that are used in Python. They are:
• in: Evaluates to true, if it finds a variable in the specified sequence
and false otherwise
• not in: Evaluates to true if it does not finds a variable in the
specified sequence and false otherwise
30. Mention the use of identity operators.
Identity operators are used to compare the memory location of two
objects. It is used to check whether the two values (variables) are
located on the same part of the memory. The variables that are equal
doesn’t mean that, they are identical. The two identify operators
used in Python. They are:
• is: Evaluates to true, if the variables on either side of the operator
point to the same object and false otherwise.
• is not: Evaluates to false, if the variables on either side of the
operator point to the same object and true otherwise.
31. Explain briefly about operator precedence
The operator precedence determines which operators need to be
evaluated first. To avoid ambiguity in values, precedence operators
are necessary.
32. Define Associativity.
Associativity is the order in which an expression is evaluated, that
has multiple operator of same precedence. Almost all the operators
have left-to-right associativity. When two operators have the same
precedence, associativity helps to determine the order of operations.
33. List out the various advantages of Python.

• Compared to other languages it is 5 to 10 times faster – Object-Oriented

36
• Dynamic Type Checking makes it inherently generic – C++ templates
for free
• Free, as in Open Source — free Portability
• Powerful language features and library
• Easy to use and learn

34. List out the various disadvantages of Python.

• Python is slow compared to C or C++ or java.


• Python is not a great choice for a high-graphic 3d game and
memory intensive tasks.
• It has some limitations with database access

Tuple Assignment

35. Define a tuple? How literals of type tuple are written? Give
example.
A tuple is a sequence data type that is similar to the list. A tuple
consists of a number of values separated by commas. Unlike lists,
however, tuples are enclosed within parentheses. They are immutable.
Syntactically, they are normally coded in parentheses instead of square
brackets, and they support arbitrary types, arbitrary nesting, and the
usual sequence operations:–

>>> T = (1, 2, 3, 4) # A 4-item tuple


>>> len(T) # Length
4
>>> T + (5, 6) # Concatenation
(1, 2, 3, 4, 5, 6)
>>> T[0] # Indexing
1
>>> T[1:3] # slicing
(2, 3)

37
36. Identify the meaning of “sequence” in python and which
three types are involved into this category?
A “sequence” is a positionally ordered collection of objects. Strings,
lists, and tuples are all sequences in Python. They share common
sequence operations, such as indexing, concatenation, and slicing,
but also have type-specific method calls. A related term, "iterable",
means either a physical sequence, or a virtual one that produces its
items on request.
37. Explain the role played by the translators in the programming
process?

Create High-level Syntax error Messages


Text Editor Translator
language program

User Inputs Run Time Other error messages


system
Program Outputs

Figure 15: Software used in the coding process

A programmer typically starts by writing high-level language statements


in a text editor. The programmer then runs another program called
translator to convert the high-level program code into executable
code. Because it is possible for a programmer to make grammatical
mistakes even when writing high-level code, the translator checks
for syntax errors before it completes the translation process. If it
detects any of these errors, the translator alerts the programmer via
error messages. The programmer then has to revise the program. If
the translation process succeeds without a syntax error, the program
be executed by the run-time system. The run-time system might
execute the program directly on the hardware or run yet another
program called interpreter or virtual machine to execute the
program. Figure 15 shows the steps and software used in the coding
38
process.
38. Explain the steps involved in interpreting a Python program

i) The interpreter reads a Python expression or statement, also


called the source code, and verifies that it is well formed. In this
step, the interpreter behaves like a strict English teacher who
rejects any sentence that does not adhere to the grammar rules,
or syntax, of the language. As soon as the interpreter encounters
such an error, it halts translation with an error message. See
figure:16.
ii) If a Python expression is well formed, the interpreter then translates
to an equivalent form in a low-level language called byte code
when the interpreter runs a script, it completely translates it to
byte code.
iii) This byte code is next sent to another software component, called
the Python virtual machine (PVM), where it is executed, If another
error occurs during this step, execution also halts with an error
message.

Syntax error
Python Code messages
Syntax Checker
and Translator

Byte Code
Other error
User Inputs messages
Python Virtual
Machine (PVM)
Program
Outputs

Figure 16: Steps in interpreting a Python Program

Modules and Functions

39. Mention the purpose of coding functions?


39
Functions are the most basic way of avoiding code redundancy in
Python—factoring code into functions means that we have only one
copy of an operation’s code to update in the future. Functions are
also the basic unit of code reuse in Python — wrapping code in
functions makes it a reusable tool, callable in a variety of programs.
Finally, functions allow us to divide a complex system into manageable
parts, each of which may be developed individually.
40. Describe when a Python function is created by the Python
interpreter?
A function is created when Python reaches and runs the def statement;
this statement creates a function object and assigns it the function’s
name. This normally happens when the enclosing module file is
imported by another module, but it can also occur when a def is
typed interactively or nested in other statements, such as ifs.
41. Describe what happens if a Python function has no return
statement in it?
A function returns the None object by default if the control flow
falls off the end of the function body without running into a return
statement. Such functions are usually called with expression statements,
as assigning their None results to variables is generally pointless. A
return statement with no expression in it also returns None.
42. Identify when does the code nested inside the function definition
statement run?
The function body (the code nested inside the function definition
statement) is run when the function is later called with a call expression.
The body runs anew each time the function is called.
43. What’s wrong with checking the types of objects passed into
a function?
Checking the types of objects passed into a function effectively breaks
the function’s flexibility, constraining the function to work on specific
types only. Without such checks, the function would likely be able
40
to process an entire range of object types—any objects that support
the interface expected by the function will work. (The term interface
means the set of methods and expression operators the function’s
code runs.)

Unit II
Big Questions

DATA, EXPRESSIONS AND STATEMENTS

1. Explain in detail about data types in python with suitable


examples
DATA TYPES

Numbers None Sequences Sets Mappings


Floating
Integer Complex Strings Tuples List Dictionary
Point
Boolean
Figure 17: List of Data Types in Python

A value is one of the fundamental things, like a letter or a number


that a program manipulates. They are grouped into different data
types or classes. Data type is a set of values and allowable operations
on those values. Data types allow programming languages to organize
different kinds of data.
Numbers: A numeric literal containing only the digits (0-9), an
optional sign character (+ or -) and a possible decimal point. Number
data types are used to store numeric values. Unlike other languages
that include several different data types for storing numbers based
on storage needs, Python creates a new object with a new memory
allocation for larger numbers. The different numerical types include:
1) int (signed integers)
2) long (long integers)
41
3) float (float integers)
4) complex (complex integers)

Table 2: Type Number


int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j

Most of the time Python will do variable conversion automatically.


We can also use Python conversion functions like (int(), long(),
float(), complex()) to convert data from one type to another. In
addition, the type function returns information about how our data
is stored within a variable.

>>>message = "Good morning"


>>>num = 85
>>>pi = 3.14159
>>> x=4+5j
>>> y=-8-2j
>>> xy=x+y
>>> print(xy)
(-4+3j)
>>>print(type(message))#This will return a string
>>>print(type(num)) #This will return an integer
>>>print(type(pi)) #This will return a float

Binary literal (base 2) A binary literal is of the form 0 (zero)


followed by either an uppercase B or lowercase b
Example:

>>> bin_num=0b1010001
>>> print(bin_num)
81
>>> print(oct(bin_num))

42
0o121
>>> print(hex(bin_num))
0x51
>>> print(type(bin_num))
<class 'int'>
>>>

In the above example we see that bin_num is a variable of type


integer. oct( and hex( are functions that convert the given input
variables to octal and hexadecimal respectively. The function type(
returns the type of the variable.
String We can create string variables by enclosing characters in
quotes. Python uses single quotes ’ double quotes “ and triple quotes
”“ to denote literal strings. Only the triple quoted strings ”“ also will
automatically continue across the end of line statement.
firstName = "baba"
lastName = "sai"
message = """This is a string that will span across multipl
>>>k="q"
>>>print("The value is %c"%k)
The value is q
>>>
Example

>>>name="Kannan"
>>>money=400
>>>print("%s took %d Rupees"%(name,money))
kannan took 400 Rupees

Boolean Boolean often called bools, are either TRUE or FALSE


condition. These two values are used when evaluating comparisons,
conditional expressions and in other structures that require values to
be represented for True or False conditions.

43
Table 3: Print Format Specifiers
Format Specifier Conversion
%c character
%s string formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERCAsE letters)
%e exponential notation (with lowercase ’e’)
%E exponential notation (with UPPER CASE ’E’)
%f floating point real number

>>> flag=True
>>> type(flag)
<class 'bool'>
Sequence A sequence is an ordered collection of items, indexed by
positive integers. It is combination of mutable and non mutable
data types. Three types of sequence data type available in Python
are Strings, Lists and Tuples Strings are already defined now we will
see about lists and tuples.
Lists: Lists are the most versatile of Python’s compound data types.
A list contains items separated by commas and enclosed within square
brackets ([]). To some extent, lists are similar to arrays in C. One
difference between them is that all the items belonging to a list can
be of different data type. The values stored in a list can be accessed
using the slice operator ([ ] and [:]) with indexes starting at 0 in the
beginning of the list and working their way to end -1. The plus (+)
sign is the list concatenation operator, and the asterisk (*) is the
repetition operator. For example, consider the following script:–
list = ['abcd', 345 , 2.23, 'maya', 70.2]
tinylist = [123, 'maya']
44
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:3]) #Prints elements starting from 2nd
till 4th
print(list[2:]) # Prints elements starting from 3rd
element
print(tinylist * 2) # Prints list two times
print(list + tinylist) #Prints concatenated lists
Output
['abcd', 345 , 2.23, 'maya', 70.2]
abcd
[345,2.23]
[2.23,'maya ',70.2]
[123,'maya ', 123,'maya']
['abcd', 345 , 2.23, 'maya', 70.2, 123,'maya']
Tuples
A tuple is another sequence data type that is similar to the list. A
tuple consists of a number of values separated by commas. Unlike
lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed
in brackets ([ ]) and their elements and size can be changed, while
tuples are enclosed in parentheses (( )) and cannot be updated.
Tuples can be thought of as read-only lists. For example:–
tuple = ( 'abcd', 456 , 2.23, 'baba', 70.2)
tinytuple = (123, 'baba')
print(tuple) # Prints complete list of tuples
print(tuple[0]) # Prints first element of the list
print(tuple[1:3]) # Prints elements starting from 2nd
till 3rd
print(tuple[2:]) # Prints elements starting from 3rd
element
print(tinytuple * 2) # Prints list two times
print(tuple + tinytuple) # Prints concatenated lists

45
Output
('abcd', 456, 2.23, 'baba', 70.2)
abcd
(456, 2.23)
(2.23, 'baba', 70.2)
(123, 'baba', 123, 'baba')
('abcd', 456, 2.23, 'baba', 70.2, 123, 'baba')
Dictionary
Python’s dictionaries are kind of hash table type. They work like
associative arrays or hashes found in Perl and consist of key-value
pairs. A dictionary key can be almost any Python type, but are
usually numbers or strings. Values, on the other hand, can be any
arbitrary Python object.
Dictionaries are enclosed by curly braces { } and values can be
assigned and accessed using square brackets []. For example :–
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name':'baba','code':6734, 'dept':'sales'}
print(dict['one']) # Prints value for ’one’ key
print(dict[2]) # Prints value for 2 key
print(tinydict) # Prints complete dictionary
print(tinydict.keys()) # Prints all the keys
print(tinydict.values()) # Prints all the values
Output
This is one
This is two
{'dept':'sales','code':6734, 'name':'baba'}
['dept', 'code', 'name']
['sales', 6734, 'baba'])

2. Prepare a Python program to exchange the value of two


variables.

46
a = int(input("enter a")
b = int(input("enter b")
print("a=",a,"b=",b)
a,b = b,a
print("a=",a,"b=",b)

3. What is a numeric literal? Give examples.


Numbers
A numeric literal containing only the digits (0-9), an optional sign
character (+ or -) and a possible decimal point.
Number data types are used to store numeric values. Unlike other
languages that include several different data types for storing numbers
based on storage needs, Python creates a new object with a new
memory allocation for larger numbers. The different numerical types
include:–
1) int (signed integers)
2) long (long integers)
3) float (float integers)
4) complex (complex integers)

Table 4: Numeric Literals


int long float complex
10 51924361L 0.0 3.14j
100 -00x1932L 15.20 45.j

Most of the time Python will do variable conversion automatically.


We can also use Python conversion functions (int(), long(), float(),
complex()) to convert data from one type to another. In addition,
the type function returns information about how our data is stored
within a variable.

>>>num = 85
>>>pi = 3.14159
47
>>> x=4+5j
>>> y=-8-2j
>>> xy=x+y
>>> print(xy) # This is a complex number
(-4+3j)
>>>print(type(num)) #This will return an integer
>>>print(type(pi)) #This will return a float

4. Discuss about the operators in Python with example.


Python is a strongly typed programming language. The interpreter
checks data types of all operands before operators are applied to
those operands. If the type of an operand is not appropriate, the
interpreter halts execution with an error message.
Consider the expression Z = X + Y.Here X, Y and Z are the operands.
The signs + and = are the operators. Python uses different operators.
They are:
1) Arithmetic Operators
2) Relational or Comparison Operators
3) Assignment Operators
4) Bit wise Operators
5) Logical Operators
6) Membership Operators
7) Identity Operators
Arithmetic Operators Arithmetic operators are used for performing
basic arithmetic operations. Python’s arithmetic expressions consists
of operators and operands. Python supports seven types of arithmetic
operations they are listed below:
Example
>>> x,y,z=40,5,3
>>> print("x+y=",x+y)
x + y = 45
48
OPERATORS

Arithmetic Relational Logical AssignmentBitwise Membership


Operators Operators Operators Operators Operators Operators
=
+ < &
+=
- > |
or -=
/ <= >> in
and /=
// >= << not in
not %=
* != ∼
//=
** = ˆ
**=
Figure 18: List of Operators in Python

>>> print("x-y=",x-y)
x - y = 35
>>> print("x * y =",x*y)
x * y = 200
>>> print("x / y =",x/y)
x / y = 8.0
>>> print("x % z == ",x%z)
x % z == 1
>>> print("x**z=",x**z)
x**2= 64000
>>> print("x floor division z=",x // z)
x floor division z= 13
>>>
Relational or Comparison Operators
Comparison operators are used to compare values. It either returns
True or False according to the condition. It describes relation between
the left and right operands. They are also called as relational operator.
The following are the relational operators:–
Example
49
Table 5: Arithmetic Operators and their usage
Ope-
rator Explanation Example
+ Addition: It adds two operands or unary plus x+y
- Subtract right operand from the left or unary minus x - y or
-x - y
* Multiplication: It multiplies values on either side x * y
of operator
/ Division: It divides left hand operand by the right x / y
hand operand
% Modulus: It also divides left hand operand by right x % y
hand operand and returns the remainder
// Floor division: The division of operands where x // y
the result is the quotient in which the digits after
the decimal point are removed. But if one of
the operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative infinity)
** Exponent: left operand raised to the power of right x ** y
Table 6: Relational Operators and their usage
Ope-
rator Explanation Example
> Greater than: True if left operand is greater than x>y
the right
< Less than: True if left operand is less than the right x <y
== Equal to:True if both operands are equal x == y
!= Not equal to: True if operands are not equal x != y
>= Greater than or equal to: True if left operand is, x >= y
greater than or equal to the right
Less than or equal to: True if left operand is less
<= than or equal to the right x <= y

50
>>> x,y=3,4
>>> print("x > y",x>y)
x > y False
>>> print("x < y",x<y)
x < y True
>>> print("x == y?",x == y)
x == y? False
>>> print("x+1<=y",x+1<=y)
x+1<=y True
>>> print("x+1>=y",x+1>=y)
x+1>=y True
>>> print("x != y",x!=y)
x != y True
>>> print("x==y?",x==y)
x==y? False
>>>

Assignment operators
Assignment operators are used in Python to assign values to variables.
a = 5 is a simple assignment operator that assigns the value 5 on the
right to the variable a on the left. There are various compound
operators in Python like a += 5 that adds to the variable and later
assigns the same. It is equivalent to a = a + 5Example
>>> x,y=5,10
>>> x=y # y is in x as well
>>> print(x)
10
>>> print("x=",x)
x= 10
>>> x+=y #10+10=20 is the new value of x
>>> print("x=",x)
x= 20
>>> x-=y #20 – 10 = 10 is the new value of x
51
Table 7: Assignment Operators and their usage
Ope-
rator Explanation Example
It Assigns values from right side operands to x=y assigns the
= left side operand value of y to x
It adds right operand to the left operand and x+=y is equivalent
+= assign the result to left operand to x = x+y
It subtracts right operand from the left x-=y is equivalent
-= operand and assign the result to left operand to x = x-y
It multiplies right operand with the left x*=y is equivalent
*= operand and assign the result to left operand to x = x*y
It divides left operand with the right operand x/=y is equivalent
/= and assign the result to left operand to x = x/y
It takes modulus using two operands and x %=y is equivalent
%= assign the result to left operand
Performs exponential (power) calculation on x**=y is
**= operators and assign value to the left equivalent to x =
operand x**y
It performs floor division on operators and x//=y is equivalent
//= assign value to the left operand to x = x//y

>>> print("x=",x)
x= 10
>>> x*=y #10 * 10 = 100 is the new value of x
>>> print("x=",x)
x= 100
>>> x,y=3,10 #x is 3 and y is 10
>>> x/=y
>>> print("x=",x)
x= 0.3
>>> x,y=10,3 #x is 10 and y is 3
>>> x%=y #x is 10 % 3 remainder after
>>> print("x=",x)#dividing 10 by 3
52
x= 1
>>> x,y=10,3 #x is 10 and y is 3
>>> x//=y #quotient after dividing 10 by 3
>>> print("x=",x) #or x = x // y
x= 3
>>> x**=y #exponentiation
>>> print("x=",x)
x= 27
>>>

Table 8: Logical Operators and their usage


Ope-
rator Explanation 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 (complements the not x
operand)

Example
>>> x,y=10,10
>>> print((x>=y) and (x ==y))
True
>>> x,y=10,5
>>> print((x>y) and (y>x))
False
>>> print((x>y) or (y>x))
True
>>> x=y
>>> print((x>y) or (y>x))
False
>>> print(not(x>y))
True
>>>
53
Membership Operators
Membership operators are used to test whether a value (variable) is
found in a sequence like string, list, tuple, set and dictionary. There
are two membership operators that are used in Python (in, not
in).Example
Table 9: Membership Operators and their usage
Ope-
rator Explanation Example
in Evaluates to true, if it finds a variable in x in y
the specified sequence and false otherwise
not in Evaluates to true if it does not finds a x not in y
variable in the I specified sequence and
false otherwise

>>> k="K.L.N. COLLEGE OF ENGINEERING"


>>> l1=k.split()
>>> e="ENGINEERING"
>>> print(e in l1)
True
>>> print('k.l.n.' in l1)
False
>>> print('K.L.N.' in l1)
True
>>> print('Science' not in l1)
True
>>>

Identity Operators
Identity operators are used to compare the memory location of two
objects. It is used to check whether the two values (variables) are
located on the same part of the memory. The variables that are equal
doesn’t mean that, they are identical. The two identity operators
used in Python are as follows:–
54
Example
Table 10: Identity Operators and their usage
Ope-
rator Explanation Example
Evaluates to true, if the variables on either
is side of the operator point to the same x is y
object and false otherwise.
Evaluates to false, if the variables on either
is not side of the operator point to the same x is not y
object and true otherwise.

>>> a='banana'
>>> b='banana'
>>> print(a == b)
True
>>> print(a is b)
True
>>> L=[1,2,3]
>>> M=L
>>> L == M
True
>>> L is M
True
>>> M = [1,2,3]
>>> M == L
True
>>> L is M
False

In the above example, variables a and b refer to the same object


’banana’ that is why is operator returns True. The first technique
here, the == operator, tests whether the two referenced objects have
the same values; this is the method almost always used for equality
55
checks in Python. The second method, the is operator, instead tests
for object identity — it returns True only if both names point to the
exact same object, so it is a much stronger form of equality testing
and is rarely applied in most programs.
Actually, is simply compares the pointers that implement references,
and it serves as a way to detect shared references in the code if
needed. It returns False if the names point to equivalent but different
objects, as is the case when we run two different literal expressions.
b L L [1,2,3]

"banana" [1,2,3]
a M M [1,2,3]

a==b[True] L==M[True] L==M[True]


a is b[True] L is M[True] L is M[False]

Figure 19: Identity Operator Functionality

5. Outline the operator precedence of arithmetic operators in


Python
The operator precedence determines which operators need to be
evaluated first. To avoid ambiguity in values, precedence operators
are necessary. The following table summarizes the operator precedence
in Python, from highest precedence (most binding) to lowest precedence
(least binding). Operators in the same row have the same precedence.
Operators are always binary unless the syntax is explicitly given.
Operators in the same row groups from left to right (except for
exponentiation, it groups from right to left).
Example
When we want to evaluate 3 + 4*5 the result would be 23 because
first the value of 4*5 is evaluated and then 3 is added to it. Suppose if
we want to add 3 with 4 and multiply it together with 5 then we must
specify it as (3+4)*5 because anything inside parenthesis is evaluated
first. In short we can remember the rule pedmas(parenthesis, exponential,
56
Table 11: Operator Precedence
Operators Explanation
** Exponentiation (raise to the power)
-,+,- Complement, unary plus and minus
*,/,%,// Multiply, divide, modulo and floor division
+,- Addition and subtraction
>>,<< Right and left bitwise shift
& bitwise ’AND’
ˆ,| Bitwise exclusive ’OR’ and regular ’OR
<=,>=,<,> Comparison Operators
==,!= Equality operators
=,%=,/=,//=,-=,+=,*=,**= Assignment operators
is,is not Identity operators
in, not in Membership operators
not,or,and Logical Operators

division, multiplication, addition and subtraction) in evaluating expressions.

>>> p,q,r,s,t=3,4,8,5,0
>>> t = (p+q)*r/s
>>> print(t)
11.2
>>> #(3+4)*8/5 = 7*8/5 = 56/5 = 11.2
>>>
6. Write a program in Python to calculate the distance between
the two points (x1, y1) and (x2, y2).
The formula for calculating the distance between the two points is:
p
distance = (y2 − y1)2 + (x2 − x1)2
We can write a Python script to determine the distance between the
two points (x1, y1) and (x2, y2) either by interactive or a scripting
method. In interactive method we can do as follows:
57
>>> x1=3
>>> y1=4
>>> x2=7
>>> y2=7
>>> distance=((y2-y1)**2+(x2-x1)**2)**0.5
>>> print(distance)
5.0
>>>

In scripting method, we can type in a function that will determine


the distance between the two points (x1, y1) and (x2, y2) as follows:

def distance(x1,y1,x2,y2):
u = x2-x1
v = y2-y1
dist = (u*u+v*v)**0.5
return dist

print(distance(3,4,7,7))

The above function together with its corresponding invocation script


is called a python module which shall be saved as a python file(with
a .py extension) and it is possible to run this module by pressing the
<F5> key from the terminal

>>>
============= RESTART: /Users/bhaskar/python/distant.py ==
5.0
>>>

Thus the given python module returned the value of the distance
between the two points (3,4) and (7,7).

58
Unit III
Short Questions

CONTROL FLOW AND FUNCTIONS

Conditionals: Boolean values and operators, conditional (if), alternative


(if-else), chained conditional (if-elif-else);

1. Define Flow control.


A program’s control flow is the order in which the program’s code
executes. The control flow of a Python program is regulated by
conditional statements, loops, control structures.
2. List the type of Python’s Decision making statements.

• if statements
• if . . . else statements
• elif statements
• nested if . . . elif . . . else statements
• inline if

3. Draw the flowchart for if statement and if-else statement in


python.
Figure 20
4. Write the syntax for if ..else and if-elif statements in Python.

if expression : if expression1 :
statements1 statements1
el se : elif expression2 :
statements2 statements2
el se :
Listing 1: Syntax for if-else staements3
See Figure 20b
Listing 2: if-elif-else

59
Test True Test False
Expression False Expression

True Statement1 Statement2

Statement Block

(a) Python if expression construct (b) Python if expression . . . else branching

Figure 20: Branching Process

In Listing 1, the expression is first evaluated if it is True, statements1


is executed if expression is False, statements2 is executed. In Listing
2, we have a if-elif-else structure. Here first of all, statements1
is executed if expression1 is True. In the event of expression1 False,
expression2 is evaluated and if True, staements2 gets executed and
if False, statements3 will get executed.
5. Write a program to check if the number is positive or negative
or zero.
numl = float(input ("Enter a number: "))
if numl >= 0:
if numl 0:
print("Zero")
else:
print (" Positive number")
else:
print ("Negative number")

6. Define Inline if statements with example.


60
An inline if statement is a simpler form of if statement and is more
if we need to perform a simple task.
Syntax
do Task A if condition is true else do Task B
Example
>>>b = True
>>>a = 1 if b else None
>>>a
Iteration: state, while, for, break, continue, pass

7. Define loops in Python.


A loop is a programming control structure that facilitates the repetitive
execution of a statement or group of statements.
8. Mention the types of looping constructs.
Python provides two types of looping constructs. They are:
1) for loop
2) while loop
9. Explain for loop with else clause.
Python supports to have an else statement associated with a loop
statement. If the else statement is used within for loop, it gets
executed when the loop has finished iterating the list. A break
statement terminates for loop iteration.
10. Write a program to find the sum of first N natural numbers
using while loop.
n = int(input("Enter the upper limit : "))
s =0
i =1
while (i <= n):
s =s+i
i =i +1
print ("Sum of first ", n, "natural numbers is", s)
61
11. Write the syntax for nested for loops in Python.
for < iterating variable > in <sequence>:
for < iterating variable > in <sequence>:
statement1(s)
statement2(s)
In the above syntax, Statement1(s) is(are) associated with inner for
and Statement2(s) is(are) associated with outer for. We must note
that the indentation that is placed makes all the difference.
12. What is the purpose of break statement in Python?
A break statement is used to end the current loop and instruct
Python to execute the statement after the loop. If it is inside a
nested loop (A loop inside another loop), break will terminate the
innermost loop. It can be used with both for and while loops.
13. What is the purpose of continue statement in Python?
The continue statement skips remaining statement(s) in the present
iteration and directs the program to the next iteration. Actually,
continue returns the control to the beginning of the loop. The
continue statement rejects all the remaining statements in the current
iteration of the loop and moves the control back to the top of the
loop.
14. Define pass statement in Python.
The use of Pass statement is to do nothing. It is just a placeholder for
a statement that is required for syntax purpose. It does not execute
any code or command. Some of the use cases for pass statement are
as follows:
Syntax purpose:

>>> while True:


... pass # Wait till user input is received
Minimal Class: It can be used for creating minimal classes:

62
>>> class MyMinimalClass:
... pass
Place-holder for TODO work: We can also use it as a placeholder
for TODO work on a function or code that needs to be implemented
at a later point of time.

>>> def initialization():


... pass #TODO
15. Outline the main functional differences between a while and
a for
The while loop is a general looping statement, but the for is designed
to iterate across items in a sequence or other iterable. Although the
while can imitate the for with counter loops, it takes more code
and might run slower.
16. Define Infinite loop with an example.
A loop becomes infinite loop if a condition never becomes False.
This results in a loop that never ends. Such a loop is called an
infinite loop.
Example:
while True:
n = int(input("Enter an integer: "))
print("The square of",n," is ", n∗∗2)

17. Write a program to find the factorial of a number.


num = int(input("Enter the number:"))
for i in range(1, num + 1):
fact = fact ∗ i
print(" Factorial of", num, "is", fact )

18. Write a program to count the number of vowels in a word


sent = input("Enter a String:") #Reads the String
count = 0
63
for letter in sent :
if letter in 'aeiouAEIOU':
count += 1
print("The number of vowels in ", sent ," is ", count)

19. Write a program to remove duplicates from a list.


lis = input("Enter a list (space separated) :")
lisl = list( lis . split ()) #converts string input to string list
uniq_items = []
for x in lisl :
if x not in uniq_items:
uniq_items.append(x)
print (uniq_items)
Output:
Enter a list(space separated) :a w e r d e w p u r y P w
['a', 'w', 'e', 'r', 'd', 'p', 'u', 'y', 'P']
>>>

20. Write a program that accept a word from the user and
reverse it.
word = input("Input a word to reverse:")
for char in range(len(word)− 1, −1, −1):
print(word[char] , end="")

Fruitful functions: return values, parameters, local and global scope,


function Composition

21. Define a function in Python.


A function is a building block of structured, reusable code that is used
to carry out a particular, interconnected action. The functions offer
improved modularity for various applications and an elevated amount
of code reusing. When the program grows larger, the functions
64
formulate it more structured and convenient. It avoids reappearance
and makes code reusable.
22.
23. Write the syntax for defining a function.
def functionname(parameters):
"""function docstring """
"function_suite"
return [expression ]
The first line of the function definition is called the header ; the rest
is called the body. The header has to end with a colon and the body
has to be indented. By convention, indentation is always four spaces.
The body can contain any number of statements. Defining a function
creates a function object, which has type function. The sentence
within triple quotes """function docstring""" is the description about
the function and function_suite is the body of the function
24. List the components required for a function definition.
A function definition consists of the following components. They are:
1) Keyword def marks the initiate of function header.
2) A function name is used to distinctively identify it.
3) The values are passed to the function with the help of parameters
(or) arguments.
4) A colon (:) is used to spot the ending of function header.
5) Optional documentation string (docstring) is exploiting to illustrate
what the function does.
6) The function body consists of one or more valid python statements.
25. Name the features of DocString?
The first string following the function header is called as the docstring
and it is a short form of documentation string. It is used to give
details in concise, what a function does. Even though optional,
65
documentation is an excellent programming practice for documenting
the code.
26. Explain how a function can be called?
Once a function has been it is feasible to call it from another function,
program or even the python prompt. A function can be called by
simply type the function name with suitable arguments. Example

>>>greet('Govind')

Output:

Hai, Govind. Have a good day!

27. Outline the use of return statement in functions?


The return statement is used to exit a function and go back to the
place from where it was called.
Syntax: return exp_list
This statement can contain expression which gets evaluated and the
value is returned. If there is no expression in the statement or the
return statement itself is not present inside a function, then the
function will return the None object.
28. Write a program using function to find the given number is
odd or even.
def odd_even(number):
if number % 2 == 0:
print("The Number", number, "is even")
else:
print("The Number", number, "is odd")
return;
result = int(input("Enter a number: "))
odd_even(result) #Call the function

29. List the advantages of functions in python.


66
• Reducing duplication of code
• Decomposing complex problems into simpler pieces
• Improving clarity of the code
• Reuse of the code
• Information hiding

30. Define scope of the variables.


Scope of a variable is the segment of a program wherever the variable
is predictable. Parameters and variables defined within a function are
not visible from outside. Therefore, they have a local scope.
31. Define Lifetime of the variables.
Lifetime of a variable is the time during which the variable exists in
the memory. The lifetime of variables within a function is as extended
as the function executes.
32. List the differences between global and local variables
Global Variables Local Variables
They are defined in the main They are defined within a
body of the program file function and is local to that
function
They can be accessed throughout They can be accessed from the
the program file. point of its definition until the
end of the block in which it is
defined.
Global variables are accessible to They are not related in any way
all functions in the program to other variables with the same
names used outside the function
33. What are the two types of functions?
Built - in functions: Built-in functions are usually a part of Python
packages and libraries.
User - defined functions: User-defined functions are written by
the developers to meet certain requirements.
67
34. What is the difference between pass by values and pass by
reference.
Pass by reference: The called function’s parameter will be the
same as the callers’ passed argument. It means that we pass the
variable itself into the function (not just the value). Pass by value:
The called functions’ parameter will be a copy of the callers’ passed
argument. It means that we pass the actual value of the variable into
the function.
35. List any three python built-in-functions.
Fn Description Example
Name
abs( ): The absolute value of a number is >>> abs(-2.5)
returned
2.5
len( ): Lenth of the string is returned >>> len('spam')
4
any( ): Any element in the iterable is True then >>> any(True,
it returns True. If there is no elements False, False)
it returns False
True
36. Write a python program to illustrate the use of enumerate()
function.
for index , element in enumerate('abc'):
print( index , element)
The result from enumerate is an enumerate object, which iterates a
sequence of pairs; each pair contains an index (starting from 0) and
an element from the given sequence. In this example, the output is:
0 a
1 b
2 c
37. Mention the advantages of user-defined function.

68
• User-defined functions aid to crumble a big program into tiny
segments which formulates program simple to understand, sustain
and debug.
• If repetitive code occurs in a program, function be capable of
including those codes and execute when wanted by calling that
function.
• Programmers’ functioning on large project can partition the workload
by building different functions.
38. List the different structures of functions with variable number
of arguments.
• Python Default Arguments
• Python Keyword Arguments
• Required arguments
• Python Variable Length (Arbitrary) Arguments
39. Discuss the arguments passed in a Python method. They
are passed by value or by reference?
Every argument in a Python method is an Object. All the variables
in Python have reference to an Object. Therefore, arguments in
Python method are passed by Reference. Since some of the objects
passed as reference are mutable, we can change those objects in a
method. But for an Immutable object like String, any change done
within a method is not reflected outside.
40. Write the syntax for defining a function with keyword arguments.

>>> #A function with two keyword arguments


>>> greeting(person_name = "Varun",message = "How are you?")

41. Define recursive function.


A function which calls by itself is a recursive function. Recursion is
the method of defining something in terms of itself.
69
42. Write a python program to find the factorial of a given
number using recursion
We can use the built-in function isinstance to verify the type of the
argument. While we?re at it, we can also make sure the argument is
positive:
def factorial (n):
if not isinstance(n, int):
print(' Factorial is only defined for integers . ' )
return None
elif n < 0:
print(' Factorial is not defined for negative integers . ' )
return None
elif n == 0:
return 1
else:
return n ∗ factorial (n−1)

43. List the advantages and disadvantages of a recursive function.


Advantages
• Recursive functions build the code appear fresh and well-designed
• A compound assignment can be broken down into simpler sub-problems
using recursion.
• Sequence generation is easier with recursion than using some
nested iteration.
Disadvantages
• On occasion the logic at the back of recursion is rigid to follow.
• The recursive calls are exclusive as they acquire up a lot of
memory and time.
• The recursive functions are rigid to debug
44. Give a brief description on anonymous function in python.

70
A function is said to be an anonymous function when it is a defined
without a name. While normal functions are defined using the def
keyword, in Python anonymous functions are defined using the lambda
keyword for a short period of time. Lambda functions can have any
number of arguments but only one expression
Syntax: lambda arguments: expression
45. Write a program to illustrate the use of lambda function
with the built-in-function map().
# Program to double each item in a list using map()
old_list = [21, 25, 24, 27, 28, 31, 33, 42]
current_list = list(map(lambda number: number ∗ 2,old_list))
print( current_list )
Output:
[42, 50, 48, 54, 56, 62, 66, 84]
Another Example
sum lambda x, y: x + y
print("Sum=", sum(3, 5))
OUTPUT
Sum = 8

Strings: string slices, immutability, string functions and methods, string


module

46. Mention the steps to Initialize String Variable in Python.


A string is defined in an assignment statement where it is enclosed
in a pair of single or double quotes.
Syntax
variable_name = ' initial string ' <or>
variable_name = " initial string "

47. Mention the use of Slicing Operator.

71
The slicing operator [:] is used to access a range of characters in a
string and to create substrings. The colon inside the square brackets
is used to separate two indices from each other Syntax
String_Variable [ start : finish −1]
Where, start: indicates the index of the initial character of the
substring finish: index of position after the substring to end
48. Given a string S with the value "s,pa,m", name two ways
to extract the two characters in the middle.
0 1 2 -3 -1

s , p a , m

[: :]

Figure 21: Offsets and slices: positive offsets start from the left end (offset
0 is the first item), and negatives count back from the right end (offset
–1 is the last item). Either kind of offset can be used to give positions in
indexing and slicing operations.

We can slice the string using S[2:4], or split on the comma and index
the string using S.split(’,’)[1]. Figure 21
49. Give an idea about replication operator.
A string or a group of strings may be repeated by using the exponential
operator (*) and a number to represent the number of times that the
string will be repeated. Here, * is the string replication operator
Syntax
(" String_variable " ∗ n)
Where, String_variable is the variable name, * is the string replication
operator, n is the number of times the string to be repeated.
50. Define Escape sequences.

72
Control characters are special characters that are not displayed on
the screen. Rather, they control the display of output. An escape
sequence is a character that gets interpreted when placed inside a
single or double quotes. They are usually represented as a backslash
notation (\).
51. Write a Python program to get the length of the string.

>>>string_a = 'Programming'
>>>len(string_a)

Lists as arrays

52. Define List.


Lists are the simplest data structure in Python and are used to
store a list of values. It is an ordered sequence of values of any
data_type(string, float, integer, etc.,). Values in the list are called
elements/items. These are mutable and indexed/ordered.
53. Write a Python program to reverse the items on a list.

>>>list1 = [1, 7, 4, 9.5, 3, 6.5, 15, 0]


>>>listl.reverse()
>>>print(list 1)
[0, 15, 6.5, 3, 9.5, 4, 7, 1]
>>>
54. Distinguish list and array in python.
Arrays and lists are both used in Python to store data, but they
don’t serve exactly the same purposes. They both can be used to
store any data type (real numbers, strings, etc), and they both can
be indexed and iterated through, but the similarities between the
two don’t go much further.
The main difference between a list and an array is the functions that
we can perform to them. For example, we can divide an array by 3,
73
and each number in the array will be divided by 3 and the result will
be printed if we request it. If we try to divide a list by 3 we need to
operate on every element in the list.
55. Translate the following for loop to equivalent while loop:
for count in range(100):
print(count)
count = 0
while(count < 100):
print(count)
count += 1

Unit III
Big Questions

CONTROL FLOW AND FUNCTIONS

Conditionals

1. Explain in detail about conditional statements in python.


Develop a Python program to find the largest among three
numbers.
Decision making constructs begins with a Boolean expression, an
expression that returns either True or False. In Python programming
zero and null values are assumed as false. Decision making structures
are necessary to perform an action or a calculation only when a
certain condition is met. In Python we have the following types
of decision making statements. They are: 1. if statement
2. if ... else statements 3. if ...elif statements 4. Inline if
5. Nested if ... elif ... else statements
Conditional if Statement
Conditional if statement starts with a Boolean expression followed
by statement or a group of statements, which evaluates the ’if’ expression
and executes the body of the program only if the evaluation is TRUE.

74
If the Boolean expression evaluates to FALSE, then the next code
after the end of if statement will be executed. In Python, the body
of if statements were indicated by the indentation. It starts with an
indentation and ends with the first un-indented line. Refer Figure 20a.
at page 60
Example
number = int(input("Enter any number from the Keyboard: "))
if number> 50:
print ("Passed")
Output
Enter any number from the Keyboard: 60
Passed
Alternative if ... else Statement
An if ... else statement block first evaluates the ’if expression’.
If the test condition is TRUE, Python executes statements in the
body of the ’if statement’. Otherwise, if the condition is FALSE,
Python executes the statements in the else block. Refer Listing 1,
page 59
if test −expression:
statements #Run when text−expression is true
else:
statements #Run when text−expression is false
Example:
a, b = 100,200
if a > b: # 100 > 200
print("a is Greater than b")
else:
print("a is Less than b")
Output:
a is Less than b
75
Test
False
Expression

True
if elif False
Block Expression

True
elif Block

else Block

Figure 22: Python if ... elif ... else statement

Chained Conditional if...elif ...else statements


An elif(else if) statement can be used when there is a need to
check or evaluate multiple expressions. An if.. .elif... else structure
first checks if the ’if Test-Expression’ is True. If it is true, then
Python executes the statements in the if block. If it is False, it tests
the condition in the elif block. If the elif Expression is evaluated as
True, Python executes the statements in the elif block. Otherwise,
control passes to the else block. Refer Listing 2 at page 59 and
Figure 22 at page 76 Example:
num = 200
if num < 100:
print("num is less than 100")
elif 100 < num < 150:

76
print("num is between 100 and 150")
else:
print("num is greater than 150")
Output:
num is greater than 150
>>>
Inline if statements
An inline if statement is a simpler form of if statement and is more
convenient, if we need to perform a simple task.
Syntax
do Task A if condition is true else do Task B
Example
>>>a = 2
>>>b = True
>>>a = 1 if b else None
"""This statement assigns 1 to a (Task A) if b is True.
Else it assigns None to a (Task B)"""
>>>a
1
2. Explain the syntax and flow chart of the following loop
statements
(i) for loops
(ii) while loop
For loops
The for loop is a simple and efficient way to step through all the
items in a sequence and run a block of code for each item in turn. For
loop iterates over a sequence that may have different data types such
as the list, tuple and string. It can also iterate any other objects that
may be defined in Python. The for-in loop repeats a given block
of codes by specified number of times. Syntax
77
for each
item in Enter while loop
sequence

Last
Yes Test False
item
Expression
reached?

No True

Body of for Body of while

Exit loop Exit loop

(a) Operation of for loop (b) while – pre-test loop

Figure 23: While and For Loops

for target in object: # Assign object items to target


statements # Repeated loop body: use target
else: # Optional else part
statements # If we didn't hit a 'break'
When Python runs a for loop, it assigns the items in the iterable
object to the target one by one and executes the loop body for
each. The loop body typically uses the assignment target to refer to
the current item in the sequence as though it were a cursor stepping
through the sequence. See Figure 23a Consider the following example:
>>> for c in 'spam':
print(c.upper())
S
P
A
M
Looping through an iterable
In Python, an iterable refers to anything that can be looped over
such as a string, list or tuple and it has the _iter_method defined.
78
metals = [' Li ' , 'Na', 'K']
for metal in metals:
print(metal,end = ' ' )
Output
Li Na K
Explanation
The first time the program runs through for loop, it assigns ’Li’ to
the variable metal. The statement print(metal) then prints the value
’Li’. The second time the program loops through for statement,
it assigns the value ’Na’ to metal and prints the value ’Na’. The
program continues looping through the list until the end of the list
is reached.
Looping through a sequence of numbers
To loop through a sequence of numbers in the form of a list, the
built-in range() function is used to iterate over for loops.
Syntax
range(start, end, step)
range() function produces the list iterates of numbers starting with
start (inclusive) and generate numbers with one less than the number
end ; step: It is the difference between each number in the sequence.
It can be negative and positive, but not zero.
If start is not given, the numbers will start from zero. If step is not
specified, a list of consecutive numbers will be generated.
Example
>>range(5)
>>list(range(5))
# If the Start value is not specified.
# It generates from 0 to end
>>range(3,10)
>>list(range(3,10))
# It starts from 3 ends with one less than the end (10)
>> range(4, 10, 2)
79
>>list(range(4,10,2))
#It generates the value from 4 (start) to 10 (end)
# with an increment of 2(step)
Output
[0,1,2,3,4]
[3,4,5,6,7,8,9]
[4,6,8]

for num in range(5):


print(num,end=? ?)

Output
0 1 2 3 4

for loop with else


Python supports to have an else statement associated with a loop
statement. If the else statement is used within for loop, it gets
executed when the loop has finished iterating the list. A break
statement terminates for loop iteration.
Program
# Program to find whether an item is present in the list
L = [10,12,13,34,27,98]
num = int(input("Enter the number to be searched in the list : "))
for item in range(len(L)):
if L[item] == num:
print("Item found at: ", (item+1))
break
else:
print("Item not found in the given list ")
Output 1

Enter the number to be searched in the list: 34


Item found at:4

80
Output 2

Enter the number to be searched in the list: 99


Item not found in the given list

While Loop
While loop is used when we need to repeatedly execute a statement
or group of statements, while the test condition is True. When the
test condition is no longer true, program control passes to the line
after the loop.
Syntax
while Boolean−expression:
Statement 1
Statement 2
...
Statement n
Program 1
# Program to print the numbers from 0 to 4
counter = 0
while(counter < 4):
print('Count is : ' , counter)
counter = counter + 1
print ("Exit of the loop!")
Output

Count is: 0
Count is: 1
Count is: 2
Count is: 3
Exit of the loop!

The flow-chart is shown in Figure 23b


Example
81
n = int(input("Enter the upper limit : "))
s =0
i =1
while (i <= n):
s =s+i
i =i +1
print ("Sum of first ", n, "natural numbers is", s)
Output

Enter the upper limit: 5


Sum of first 5 natural numbers is 15

Explanation In the above program, when the text Enter the upper
limit appears, 5 is given as the input. i.e., n = 5. Initially, a counter i
is set to 1 and sum is set to 0. When the condition is checked for the
first time i <= n, it is True. Hence the execution enters the body of
while loop. Variable sum is added with i and i is incremented. Since
the next statement is un-indented, it assumes the end of while block
and again go back to check the condition. This process is repeated
until the condition given in the while loop is False and the control
goes to the next print statement to print the sum.
NESTED LOOPS
Nesting is defined as the placing of one loop inside the body of
another loop. When we "nest" two loops, the outer loop takes control
of the number of complete repetitions of the inner loop. While all
types of loops may be nested, we can have nested loops for both while
and for loops.
Syntax for nested for loop

for < iterating_variable > in <sequence>:


for < iterating_variable > in <sequence>:
Statement(s)
Statement(s)

82
Syntax for nested while loop

while test_expression:
while test_expression:
Statement(s)
Statement(s)
Program 1

# Program to generate prime numbers using for loop


num = int(input("Enter a Limit:"))
for a in range(1,num):
k = int(a/2)
for b in range(2, k + 1):
if a % b == 0:
break
else:
print(a,end=" ")

Enter a Limit:30
1 2 3 5 7 11 13 17 19 23 29

3. Explain break and continue statement with the help of for


loop in an example.
CONTROL STATEMENTS
Control statements change the execution from normal sequence. i.e.
It controls the flow of program execution to get desire behaviour or
result. Loops iterate over a block of code until test expression is false,
but sometimes we wish to terminate the current iteration or even the
whole loop without checking test expression. The break and continue
statements are used in these cases. Python supports the following
three control statements:
1) break
83
2) continue
3) pass
Control statement Meaning
It terminates the loop statement and
break transfers execution to the statement
immediately following the loop.
Causes the loop to skip the remainder of its
continue body and immediately retest its condition
prior to reiterating.
The pass statement in Python is used when
a statement is required syntactically but we
pass
do not want any command or code to
execute.
Break Statement
A break statement is used to end the current loop and instruct
Python to execute the statement after the loop. If it is inside a
nested loop (A loop inside another loop), break will terminate the
innermost loop(Figure 24). It can be used with both for and while
loops. It is commonly used when a quick exit is required.
Continue Statement
The continue statement skips remaining statement(s) in the present
iteration and directs the program to the next iteration. continue
returns the control to the beginning of the loop. The continue
statement rejects all the remaining statements in the current iteration
of the loop and moves the control back to the top of the loop. The
continue statement can be used in both while and for loops.
Example(break)
num = 0
breakn = int(input("Enter when to break(n<10):"))
while (num < 10):
if (num == breakn):
break
print(num,end =" ")
84
Enter
while
or for
loop

Range or
other True
Expressions

Rest of
if False
for / while
Condition?
iterations

False
True

break

Figure 24: Python break statement

num = num + 1
print("End of Program")
Enter when to break(n<10):4
0 1 2 3 End of Program

Explanation
"if (num == breakn): break" will run the "break" command if num
is 4, the break statement will exit from the while loop, and run
"print(End of Program")
The continue statement
The continue statement causes an immediate jump to the top of a
loop(figure 25). It also sometimes lets us avoid statement nesting.
The next example uses continue to skip odd numbers. This code
prints all even numbers less than 10 and greater than or equal to

85
Enter
while
or for
loop

Range or
other True
Expressions

Rest of
if False
for / while
Condition?
iterations

False
True

continue

Figure 25: Python continue statement

0. Also, we must remember that the value 0 means False thus it


terminates the while loop when x decrements to 0
Example Program
x = 10
while x:
x = x−1 # Or, x −= 1
if x % 2 != 0:
continue # Odd? −− skip print
print(x, end=' ')
Output
8 6 4 2 0
>>>
4. Differentiate for loop and while loop.
86
for loop while loop
for is designed to iterate across
The while loop is a general
items in a sequence or other
looping statement
iterable
The for loop will run exactly n The while loop will not
times run n times
The for loop in python is very
powerful so it is very frequently while loop is rarely used
used
5. Explain briefly the function definition and calling in Python.
Functions are the most basic way of avoiding code redundancy in
Python?factoring code into functions means that we have only one
copy of an operation?s code to update in the future
1) Function blocks start with the keyword def followed by the function
name and a pair of parentheses ( ).
2) A function name is used to distinctively identify it. Function
identification follows the same convention of writing identifiers in
Python.
3) The values are passed to the function with the help of parameters
(or) arguments. Any input parameters (or) arguments are supposed
to be placed inside these parentheses. They are not obligatory
(Compulsory).
4) A colon (:) is used to spot the end of function header.
5) Optional documentation string (docstring) is exploiting to illustrate
what the function does.
6) The function body consists of one or more valid python statements.
Statements should have similar indentation level (usually 4 spaces).
A discretionary return statement is used to return a value from
the function. The statement return [expression] leaves a function,
optionally by passing back an expression to the caller. A return

87
statement with no arguments is same as return None. Syntax

def functionname(parameters):
"""function_docstring"""
function suite
return[expression ]
By default, parameters have a positional performance and it is compulsory
to enlighten them in the similar order that they were defined. Program
def Greeting(name = "Everyone"):
""" Greeting the person """
print("Hai " + name + "!")
Greeting("Sai")
Greeting ()
Output
Hai Sai!
Hai Everyone!

FUNCTION CALL
Once a function has been defined, it is feasible to call it from another
function, program or even the python prompt. A function can be
called by simply type the function name with suitable arguments.

>>>Greeting ('Sai')
Hai, Sai!

Pass by Reference vs. Pass by Value


Arguments are passed neither by value and nor by reference in
Python - instead they are passed by assignment. The parameter
passed in is actually a reference to an object, as opposed in reference
to a fixed memory location but the reference is passed by value. In
addition, some data types (like strings, tuples etc.,) are immutable
whereas others are mutable.
The return statement
88
Define a function called

Name of function

inputs

colon

def: greeting (name="Everyone") :

""" This function will greet the person


whose name is passed as a parameter"""
Body of function
print("Hai,"+name +"!")
Greeting( )

Figure 26: Python Function Definition

A function may have a return[expression] statement. That is, the


return statement is optional.
Local and Global Variables
A variable which is defined within a function is local to that function.
A local variable can be accessed from the point of its definition until
the end of the function in which it is defined. It exists as long as
the function is executing. Function parameters behave like local
variables in the function. Moreover, whenever we use the assignment
operator (=) inside a function, a new local variable is created. Global
variables are those variables which are defined in the main body of
the program file. They are visible throughout the program file. As
a good programming habit, we must try to avoid the use of global

89
variables because they may get altered by mistake and then result in
erroneous output.
num1 = 10 #global variable
print("Global variable num1 = ", num1)
def func(num2): # num2 is function parameter
print("In Function − Local Variable num2 = ",num2)
num3 = 30 #num3 is a local variable
print("In Function − Local Variable num3 = ",num3)
func(20) #20 is passed as an argument to the function
print("num1 again = ", num1) #global variable is being accessed
#Error− local variable can't be used outside the function in which
#it is defined
print("num3 outside function = ", num3)
Output

Global variable num1 = 10


In Function - Local Variable num2 = 20
In Function - Local Variable num3 = 30
num1 again = 10
Traceback (most recent call last):
File "/Users/bhaskar/Documents/Python/output01.py", line 10
print("num3 outside function = ", num3)
NameError: name 'num3' is not defined
>>>

Keyword Arguments When we call a function with some values,


the values are assigned to the arguments based on their position.
Python also allow functions to be called using keyword arguments in
which the order (or position) of the arguments can be changed. The
values are not assigned to arguments according to their position but
based on their name (or keyword). Keyword arguments are beneficial
in two cases.
First, if we skip arguments. Second, if in the function call you change the

90
def display (str_a, int_x, float_y) :
print('The string is : ' ,str_a)
print('The integer value is : ' ,int_x)
print('The floating point value is : ' ,float_y)
display (float_y = 56789.045, str_a = 'Hello' , int_x =1234)
OUTPUT
The string is : Hello
The integer value is : 1234
The floating point value is: 56789.045
>>>
Default Arguments
Python allows users to specify function arguments that can have
default values. This means that a function can be called with fewer
arguments than it is defined to have. That is, if the function accepts
three parameters, but function call provides only two arguments,
then the third parameter will be assigned the default (already specified)
value. The default value to an argument is provided by using the
assignment operator (=). Users can specify a default value for one
or more arguments.
Example
def display (name, course = "BTech"): # Default Argument for course
print("Name : " + name)
print("Course : ", course)
display (course = "B.E", name = "Jegan") # Keyword Arguments
display (name = "Nabin")
OUTPUT
Name : Jegan
Course : B.E
Name : Nabin
Course : BTech
>>>
91
In the above code, the parameter name does not have a default value
and is therefore mandatory. That is, we must specify a value for
this parameter during the function call. But, parameter, course has
already been given a default value, so it is optional. If a value is
provided, it will overwrite the default value and in case a value is
not specified during function call, the one provided in the function
definition as the default value will be used.
Variable-length Arguments
In some situations, it is not known in advance how many arguments
will be passed to a function. In such cases, Python allows programmers
to make function calls with arbitrary (or any) number of arguments.
When we use arbitrary arguments or variable-length arguments, then
the function definition uses an asterisk (*) before the parameter
name. Syntax for a function using variable arguments can be given
as,
def functionname([argl , arg2, .... ] ∗var_args_tuple ):
function statements
return [expression ]
def func(name, ∗fav_subjects):
print("\n", name, " likes to read ")
for subject in fav_subjects :
print(subject)
func("Narayanan", "Mathematics", "Android Programming")
func("Neeraja", "Machine Learning", "Data Structures", "Design and An
func("Mittal")
OUTPUT
Narayanan likes to read
Mathematics
Android Programming
Neeraja likes to read
Machine Learning
Data Structures
92
Design and Analysis of Algorithms
Mittal likes to read
>>>

6. Explain in detail about iterations in python


The for loop and the while loop can be combined with loop control
statements to create various loop/iteration forms.
Loops are classified as the following:
• Infinite Loop
• Loop with condition at the top(pre test)
• Loop with condition at middle(sentinel loop)
• Loop with condition at bottom(post test)
A loop becomes infinite loop if a condition never becomes False. This
results in a loop that never ends. Such a loop is called as an infinite
loop. The infinite loop is formed with the while statement. We
get an infinite loop when the specified test condition is always true.
Program
# To exit from the loop press Ctrl + c
while True:
n = int(input("Enter an integer: "))
print("The double of",n," is ",2 ∗ n)

Enter an integer: 4
The double of 4 is 8
Enter an integer: 8
The double of 8 is 16
Enter an integer: 10
The double of 10 is 20
Enter an integer:
Traceback (most recent call last):
File "/Users/bhaskar/Documents/Python/infiniteloop.py", lin
n = int(input("Enter an integer: "))
93
KeyboardInterrupt
>>>

Loop with condition at the top


A while loop with a condition placed at the top is a standard while
loop with no break statements. The loop ends when the condition
becomes False. Program
# To illustrate a loop with condition at the top
num = 10 # Initialize sum(s) and counter( i )
s =0
i =1
while i <= num:
s =s+i
i = i + 1 # Update counter
print("The sum is",s)

Output
The sum is 55
>>>

Loop with condition at middle Example


#Program ∗ To illustrate a loop with condition in the middle
vowels = "AEIOUaeiou"
while True:
a = input("Enter a vowel: ")
# Condition in the middle
if a in vowels :
break
print("That is not a vowel. Try again!")
print(" Finally , a Vowel has been Entered!")
Output

Enter a vowel: t

94
That is not a vowel. Try again!
Finally, a Vowel has been Entered!
Enter a vowel: u
>>>
Loop with condition at bottom This kind of loop ensures that
the body of the loop is executed at least once. It can be implemented
using an infinite loop along with a conditional break at the end. This
is similar to the do...while loop in C.
#Program To illustrate a loop with condition at the bottom
num1, num2 = 6, 3
choice = 1
print(num1,num2)
while choice != 5:
print("Menu")
print("l . Addition")
print("2. Subtraction")
print("3. Multiplication ")
print("4. Division ")
print("5. Exit")
choice = int(input("Enter your choice:"))
if choice == 1: print ("Sum=", (num1 + num2))
if choice == 2: print ("Difference =", (num1 − num2))
if choice == 3: print ("Product=", (num1 ∗ num2))
if choice == 4: print ("Quotient=", (num1 / num2))
if choice == 5:
break;
print("End of Program")
Output
6 3
Menu
l. Addition
2. Subtraction
95
3. Multiplication
4. Division
5. Exit
Enter your choice:1
Sum= 9
End of Program
Menu
l. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice:2
Difference = 3
End of Program
Menu
l. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice:5
>>>

7. Explain any three built-in string methods in Python.


Consider the following example:

>>> S='spam'
>>> result=S.find('pa') # call function to find 'pa' in S
>>> result
1

96
Function Description Example
Capitalizes first letter of >>> S='maria'
capitalize()
string >>> S.capitalize()

'Maria'

Counts how many times


sub occurs in string or in a
count(sub [, >>> S = 'College of Computer
substring of string if
start [, end]]) and Information Science'
starting index start and
>>> S.count(’Co’,0,len(S)
ending index end are given
2

Returns True if S contains


isalpha() only letters or False >>> S = 'Hi, there!'

otherwise. >>> S.isalpha()

False

8. Develop a program to find whether the given number is odd


or even.
def odd_even(n):
if n%2 == 0:
print('The number is Even')
else:
print('The number is Odd')
return
odd_even(8)
odd_even(11)
Output
The number is Even
The number is Odd
>>>
9. Write a program to concatenate all elements in a list into a
string and return it.
Let us assume that we have a list = [1,5,8,13,7,4]. This can be
visualized as shown in Figure 27. We can develop a functio called
97
concatenate_list_data with list as an argument to it. As list is
an iterative object, we can traverse over it and pick out each element
in every iteration using a for loop and combine them together using
the concatenate operator "+". Next, we can return the result.
def concatenate_list_data(list) :
result = ''
for element in list :
result += str(element)
return result

print(concatenate_list_data([1, 5, 8, 13, 7, 4]) )


Output

1581374
>>>

1 5 8 13 7 4

concatenate()

1581374

Figure 27: List concatenation

10. Explain recursive function. How do recursive function works?


Explain with a help of a program.
Recursion is a somewhat advanced method/topic, and it’s relatively
rare to see in Python, partly because Python’s procedural statements
include simpler looping structures. Still, it’s a useful technique to
know about, as it allows programs to traverse structures that have
arbitrary and unpredictable shapes and depths – planning travel

98
routes, analyzing language, and crawling links on the Web, for example.
Recursion is even an alternative to simple loops and iterations, though
not necessarily the simplest or most efficient one. Let’s look at the
following example:
def countdown(n):
if n <= 0:
print(' Blastoff ! ' )
else:
print(n)
countdown(n−1)
If n is 0 or negative, it outputs the word, "Blastoff!" Otherwise,
it outputs n and then calls a function named countdown – itself –
passing n -1 as an argument. What happens if we call this function
like this?

>>> countdown(5)

The execution of countdown – Figure 28 begins with n=5, and since


n is greater than 0, it outputs the value 5, and then calls itself...
The execution of countdown begins with n=4, and since n is greater
than 0, it outputs the value 4, and then calls itself...
The execution of countdown begins with n=3, and since n is greater
than 0, it outputs the value 3, and then calls itself...
The execution of countdown begins with n=2, and since n is greater
than 0, it outputs the value 2, and then calls itself...
The execution of countdown begins with n=1, and since n is greater
than 0, it outputs the value 1, and then calls itself...
The execution of countdown begins with n=0, and since n is not
greater than 0, it outputs the word, "Blastoff!" and then returns.
That returns to the __main__
11. Generate a program that uses lambda function to multiply
two numbers

99
5
4
3
2
1
Blastoff!
>>>

Figure 28: Printing Recursive function

>>> multi = lambda x,y: x*y


>>> print(multi(3,4))
12
>>>

Here multi is a lambda function which requires two arguments x and


y which when given, returns the product of x and y.
12. Discuss the methods to manipulate the arrays in python
One nice feature of Python’s core data types is that they support
arbitrary nesting – we can nest them in any combination, and as
deeply as we like. For example, we can have a list that contains a
dictionary, which contains another list, and so on. One immediate
application of this feature is to represent matrixes, or "multidimensional
arrays" in Python. A list with nested lists will do the job for basic
applications (we’ll get "..." continuation-line prompts on lines 2 and
3 of the following in some interfaces, but not in IDLE):

>>> M=[[1,2,3],
... [4,5,6],
... [7,8,9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>>

Here, we’ve coded a list that contains three other lists. The effect
100
is to represent a 3 × 3 matrix of numbers. Such a structure can be
accessed in a variety of ways:

>>> M[1] #get row 2


[4, 5, 6]
>>> M[1][2]. #Get row 2, then get item 3 within the row
6
>>>

The first operation here fetches the entire second row, and the second
grabs the third item within that row (it runs left to right, like the
earlier string strip and split). In addition to sequence operations and
list methods, Python includes a more advanced operation known as
a list comprehension expression, which turns out to be a powerful
way to process structures like our matrix.
13. Create a program to reverse a string without using any
built-in functions
There are various ways to reverse a string in python. Let us see
a few:
def reverse1(s) : def reverse2(s) :
str1 = "" if len(s) == 0:
return s
for i in s : else:
str1 = i + str1 return reverse2(s [1:]) + s[0]
return str1
Listing 4: using recursion
Listing 3: reverse using loop
In above code Listing 3, we call a function reverse1 to reverse a
string, which iterates to every element and intelligently join each
character in the beginning so as to obtain the reversed string. Similarly
in Listing 4, the string is passed as an argument to a recursive
function reverse2 to reverse the string. In the function, the base
condition is that if the length of the string is equal to 0, the string
is returned. If not equal to 0, the reverse function is recursively

101
called to slice the part of the string except the first character and
concatenate the first character to the end of the sliced string.
14. Illustrate a program to find GCD of m and n.
m = int(input("Enter a number:"))
n = int(input("Enter another number:"))
rem = m % n
while rem != 0 :
m=n
n = rem
rem=m % n
print ("gcd of given numbers is :", n)

Listing 5: GCD of two numbers


Output
Enter a number:30
Enter another number:18
gcd of given numbers is : 6
>>>

15. How to find the square root of a number using newton’s


method
According to Newton-Raphson method, suppose if we want to find
the roots of a finction y = f (x), we can use the iterative version of
this method by calculating the value of xn+1 in terms of xn, as given
by the following formula:
f (xn)
xn+1 = xn − (8)
f 0(xn)
where f 0(x) as usual the first derivative of the function f (x). Since

we want to calculate x = c where c is any variable, let us convert
it into an equation form by f (x) = x2 − c = 0; ⇒ f 0(x) = 2x and

102
f (x)

f (x) = x2 − 3

f (x0 )

f (x1 )
α
x
x1 x0

Figure 29: Newton’s method

putting this in the equation (8) we get


x2n − c
xn+1 = xn −
2xn
2x2n − x2n + c 1
 
c
= = xn + (9)
2xn 2 xn
As shown in Figure 29, we have typically, set-up a curve for the
function f (x) = x2 − 3 for calculating the square root of √3. Though
it is not correct, let us choose x0 = 3 and c = 3 obviously, 3 6= 3, we
still can understand this algorithm’s behaviour towards the solution.
Next, we get
1 c 1 + 3
x1 = 1+ = =2
2 1 2
similarly,  
1 3 7
x2 = 2+ = = 1.75
2 2 4
103
 
1 3 1
x3 = 1.75 + = (1.75 + 1.714) = 1.732
2 1.75 2
Intuitively, these results motivates us in bringing the following algorithm 4
for calculating the square-root of a number using Newton-Raphson
method: Using the same algorithm we can develop the Python function 6
1. x←3
2. approximation ← 3
3. iterations ← 5
4. for i = 1 to iterations do
5. better_approximation ← 0.5 × (approximation +
x/approximation)
6. approximation ← better_approximation
7. print better_approximation
Algorithm 4: Algorithm for Square-Root

for calculating the square root of a number which is given as follows:


c=int(input("Enter number for square root:"))
maxiter=int(input("Enter maximum iterations:"))
xn=1
for i in range(maxiter):
xnplusone=0.5∗(xn+c/xn)
xn=xnplusone
print(xn)

Listing 6: Square Root in Python by Newton’s method

Unit IV
Short Questions

LISTS, TUPLES, DICTIONARIES

list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists,
list parameters

1. Define a list
104
Lists are the simplest data structure in Python and are used to
store a list of values. It is an ordered sequence of values of any
data_type (string, float, integer, etc.,). Values in the list are called
elements/items. These are mutable and indexed/ordered.
2. Describe the way to slice a list in python.
The values stored in a list can be accessed using slicing operator,
the colon (:) with indexes starting at 0 in the beginning of the list
and ending with -1. It is used to access a range of elements on lists.
Syntax
list_name[start:finish-1]
3. Explain about how to concatenate a list in python.
It is possible to concatenate or combine two or more lists in Python
with the (+) operator. The (+) sign is the list concatenation operator.
4. Explain about how to repeat a list in python.
To repeat a list, we can use the(*)operator and a number to specify
the number of times the list to be repeated. Here the asterisk (*)
sign is the repetition operator.
5. Determine the output of print(list[0])if
list = [’abcd’,29,2.23,’john’,70.2]?
It will print first element of the list. Output would be abcd.
6. Determine the output of print(list[1:3]) if
list = [’abcd’,23,2.23,’john’,70.2]?
It will print elements starting from 2nd till 3rd. Output would be
[23, 2.23].
7. Consider the following three statements. Do they change
the value printed for A?
A = "spam"
B = A
B = "shrubbery"

105
No: A still prints as "spam". When B is assigned to the string
"shrubbery", all that happens is that the variable B is reset to point
to the new string object. A and B initially share (i.e., reference/point
to) the same single string object "spam", but two names are never
linked together in Python. Thus, setting B to a different object has
no effect on A. The same would be true if the last statement here
were B = B + ’shrubbery’, by the way – the concatenation would
make a new object for its result, which would then be assigned to B
only. We can never overwrite a string (or number, or tuple) in place,
because strings are immutable.
8. Consider these three statements. Do they change the printed
value of A?

A = ["spam"]
B = A
B[0] = "shrubbery"
Yes: A now prints as ["shrubbery"]. Technically, we haven’t really
changed either A or B; instead, we’ve changed part of the object
they both reference (point to) by overwriting that object in place
through the variable B. Because A references the same object as B,
the update is reflected in A as well.
9. Determine the output of print(list[2:]) if
list = [’abcd’,786,2.23,’john’,70.2]?
It will print elements starting from 3rd element. Output would be
[2.23, ’john’, 70.2].
10. Determine the output of print(tinylist * 2) if
tinylist = [123,’john’]?
It will print list two times.Output would be [123,’john’,123,’john’]
11. Determine the output of print(list + tinylist * 2) if
list = [ 'abcd',786,2.23,'john',70.2] and
tinylist = [123,'john']?

106
It will print the concatenated lists. Output would be
['abcd',786,2.23,'john',70.2,123,'john',123,'john']
12. Define append() and extend().
Lists are mutable, hence we can easily add an element or a range
of elements on a list with the append() or extend() method. The
append() method is used to add a single item while the extend()
method is used to append two or more items. Both methods are
used to add items at the end of the original list.
Syntax
list_name.append(object) # Append method
list_name.extend(seq) # Extend method

13. Describe the way to remove an item from the list in python.
To remove an item from a list, we can use either the remove() or
the pop() method.
• remove() method
The remove() method removes the specified item.
Syntax
list_name.remove(object)

• The pop() method


The pop() method is used to remove the item associated with
the given index. If the index is not given, it removes and returns
the last element on the list.
Syntax
list_name.pop(index)
14. Describe how to reverse an item from the list in python?
To arrange or view the items in the reverse or descending order, we
can use Python’s reverse method.
Syntax
list_name.reverse()

107
15. Explain map() with an example.
The function applies a passed-in function to each item in an iterable
object and returns a list containing all the function call results.
Example
str= input("Enter a list :")
lis =list(map(int,str.split() ))
print( lis )

16. Define about tuples in Python.


A tuple is another sequence data type that is similar to the list. A
tuple consists of a number of values separated by commas. Unlike
lists, however, tuples are enclosed within parentheses.
17. Mention the difference between tuples and lists in Python.
The main differences between lists and tuples are, Lists are enclosed
in brackets ( [ ] ) and their elements and size can be changed, while
tuples are enclosed in parentheses ( ) and cannot be updated. Tuples
can be thought of as read-only lists.
18. Describe the way to reassign the values to the tuple?
To reassign a tuple, list a different set of elements and assign it to
the tuple.
>>>my_tuple = ('c', 'o', 'd', 'e', 'r')
19. What is the use of enumerate( ) in python?
Using enumerate() function we can iterate through the sequence and
retrieve the index position and its corresponding value at the same
time.

>>> for i,v in enumerate(['Python' ,'Java','C++']):


print(i,v)

Output

0 Python
108
1 Java
2 C++

20. Define Mapping.


A mapping object maps immutable values to arbitrary objects. Mappings
are mutable objects. There is currently only one standard mapping
type, the dictionary.
21. Mention the features of Python’s dictionaries.
Python’s dictionaries are kind of hash table type. They work like
associative arrays or hashes found in Perl and consist of key-value
pairs. A dictionary key can be almost any Python type, but are
usually numbers or strings. Values, on the other hand, can be any
arbitrary Python object.
22. Describe the way to create a dictionary in python
Dictionaries are enclosed by curly braces ( ) and values can be assigned
and accessed using square braces ([])
dict = {}
dict[ 'one' ] = "This is one"
dict[2] = "This is two"

23. Mention the steps to get all the keys from the dictionary
Using dictionary.keys() function, we can get all the keys from the
dictionary object. print dict.keys() #Prints all the keys
24. Mention the way to get all the values from the dictionary
Using dictionary.values() function, we can get all the values from the
dictionary object. print dict.values() # Prints all the values
25. Distinguish between mutable and immutable objects?
Objects whose value can change are said to be mutable and objects
whose value is unchangeable once they are created are called immutable.
An object’s mutability is determined by its type.

109
26. Define reduce() in Python.
It takes a binary function and some list of values and typically
produces a single value: it reduces or accumulates these results into a
single value. Unlike map and filter (which are defined and automatically
imported from the built-ins module) we must import reduce from the
functools module explicitly. Syntax
r = reduce(function, sequence)
27. Define list comprehension.
List comprehensions are a tool for transforming one list (any iterable
actually) into another list. List comprehensions provide an alternative
syntax to creating lists and other sequential data types. While other
methods of iteration, such as for loops, can also be used to create
lists, list comprehensions may be preferred because they can limit
the number of lines used in our program.
Syntax
[ expression for item in list if conditional ]

28. Name four iteration contexts in the Python language


Iteration contexts in Python include the for loop; list comprehensions;
the map built-in function; the in membership test expression; and the
built-in functions sorted, sum, any, and all. This category also
includes the list and tuple built-ins, string join methods, and
sequence assignments, all of which use the iteration protocol (see
answer 29) to step across iterable objects one item at a time.
29. Explain how for loops and iterable objects are related?
The for loop uses the iteration protocol to step through items in the
iterable object across which it is iterating. It first fetches an iterator
from the iterable by passing the object to iter, and then calls this
iterator object’s __next__ method in 3.X on each iteration and
catches the StopIteration exception to determine when to stop
looping. The method is named next in 2.X, and is run by the next
built-in function in both 3.x and 2.X. Any object that supports this
110
model works in a for loop and in all other iteration contexts. For
some objects that are their own iterator, the initial iter call is
extraneous but harmless.
30. Name two ways to build a list containing five integer zeros.
A literal expression like [0, 0, 0, 0, 0] and a repetition expression like
[0] * 5 will each create a list of five zeros. In practice, we may also
build one up with a loop that starts with an empty list and appends
0 to it in each iteration, with L.append(0). A list comprehension ([0
for i in range(5)]) could work here.
31. Name two ways to build a dictionary with two keys, 'a'and
'b', each having an associated value of 0.
A literal expression such as 'a': 0, 'b': 0 or a series of assignments like
D = , D['a'] = 0, and D['b'] = 0 would create the desired dictionary.
We can also use the newer and simpler-to-code dict(a=0, b=0)
keyword form, or the more flexible dict([('a', 0), ('b', 0)]) key/value
sequences form. Or, because all the values are the same, we can use
the special form dict.fromkeys('ab', 0). In 3.X and 2.7, we can also
use a dictionary comprehension: k:0 for k in 'ab'.
32. Name four operations that change a dictionary object in
place.
Dictionaries are primarily changed by assignment to a new or existing
key, which creates or changes the key’s entry in the table. Also, the
del statement deletes a key?s entry, the dictionary update method
merges one dictionary into another in place, and D.pop(key) removes
a key and returns the value it had.
33. Give the reason for using a dictionary rater than a list.
Dictionaries are generally better when the data is labeled (a record
with field names, for example); lists are best suited to collections
of unlabeled items (such as all the files in a directory). Dictionary
lookup is also usually quicker than searching a list, though this might
vary per program.
111
Unit IV
Big Questions

Lists

List methods

1. Define Lists. Explain built-in List methods with suitable


examples.
Lists are the simplest data structure in Python and are used to
store a list of values. It is an ordered sequence of values of any
data_type (string, float, integer etc.,). Values in the list are called
elements/items. These are mutable and indexed ordered. To create
a list, we define a variable to contain an ordered series of items
separated by a comma. A square bracket is used to enclose the
items.
Syntax
my_list = [] # To create an empty list
my_list = [iteml , item2, item3, item4] #To create a list of items

Example 1.
num_list = [0, 5, 10, 15, 50, 14) # List with integers
string_list = ["cat", " lion ", " tiger ", "zebra"] # Strings
# List with mixed data types
mixed_list = [18, " publishers ", 35.5]
# List with nested list
nested list = ["keyboard", 8.5, 6, [5, 1, 3, 4, 5.5, 2]]

Example 2.
First_year = ["English", "Chem", "Phys", "Math", "Python"]

Built in List Methods


Adding Elements to the end of a List
Lists are mutable, Hence we can easily add an element or a range
of elements on a list with the append() or extend() method. The

112
Table 12: List Indexing and its contents

Index 0 1 2 3 4
String English Chem Phys Math Python

append() method is used to add a single item while the extend()


method is used to append two or more items. Both methods are
used to add items at the end of the original list. These methods
are summarised in Table 13 where L refers to a list. To learn more
about these methods, enter help(list) in a Python shell. The
List Method Description
L.append(element) Adds element to the end of L.
Adds the elements of aList to the
L.extend(aList)
end of L
Inserts element at index if index
L.insert(index, is less than the length of
element) L.Otherwise, inserts element at the
end of L
Removes and returns the element at
L.pop()
the end of L
Removes and returns the element
L.pop(index)
at index.
deletes the first occurrence of e
L.remove(e)
from L.
sorts the elements of L in ascending
L.sort()
order
reverses the order of the elements in
L.reverse()
L.

Table 13: List methods for inserting and removing elements

method insert expects an integer index and the new element as

113
arguments. When the index is less than the length of the list, this
method places the new element before the existing element at that
index, after shifting elements to the right by one position. At the end
of the operation, the new element occupies the given index position.
When the index is greater than or equal to the length of the list, the
new element is added to the end of the list. Example 3 shows insert
in action:
Example 3.
>>> example = [1, 2)
>>> example
[1, 2)
>>> example.insert(1, 10)
>>> example
[1, 10, 2)
>>> example.insert(3, 25)
>>> example
[1, 10, 2, 25)
>>>

The method append is a simplified version of insert. The method


append expects just the new element as an argument and adds the
new element to the end of the list. The method extend performs a
similar operation, but adds the elements of its list argument to the
end of the list. Example 4 shows the difference between append and
extend
Example 4.
>>> example [1, 2]
>>> example
[1, 2]
>>> example.append(10)
>>> example
[1, 2, 10]
>>> example.extend(11,12,13)
114
>>> example
[1, 2, 10, 11, 12, 13]
>>>

The method pop is used to remove an element at a given position.


If the position is not specified, pop removes and returns the last
element. If the position is specified, pop removes the element at that
position and returns it. In that case, the elements that followed the
removed element are shifted one position to the left. To empty a list,
we can use the clear() method. The remove() method removes
the specified item from the list. Example 5 removes the last and first
elements from the example list also remove() and clear()methods
are shown:
Example 5.
>>> example
[1, 2, 10, 11, 12, 13]
>>> example.pop()
13
>>> example
[1, 2, 10, 11, 12]
>>> example.pop(0)
1
>>> example
[2, 10, 11, 12]
>>> numbers = [1, 3, 5, 6.5, 7, 7.5, 9]
>>> numbers.remove(6.5)
>>> numbers.remove(7.5)
>>> numbers
[1, 3, 5, 7, 9]
>>> numbers.clear()
>>> numbers
[]
>>>

115
When using a list, we can change its contents by assigning to either a
particular item (offset) or an entire section (slice). Consider Example 6:

Example 6.
>>> L = ['spam', 'Spam', 'SPAM!']
>>> L[1] = 'eggs'
>>> L
['spam', 'eggs', 'SPAM!']
>>> L[0:2] = ['eat','more']
>>> L
['eat', 'more', 'SPAM!']
>>>
2. Explain in detail about cloning
Consider the following example,
def removeDups(L1, L2):
"""Assumes that L1 and L2 are lists . Removes any element from
L1 that also occurs in L2"""
for e1 in L1:
if e1 in L2:
L1.remove(e1)
print(e1)
L1 = [1,2,3,4]
L2 = [1,2,5,6]
removeDups(L1, L2)
print('L1 =', L1)
Output
1
3
4
L1 = [2, 3, 4]
>>>
116
Explanation During a for loop, the implementation of Python
keeps track of where it is in the list using an internal counter that
is incremented at the end of each iteration. When the value of the
counter reaches the current length of the list, the loop terminates.
This works as one might expect if the list is not mutated within the
loop, but can have surprising consequences if the list is mutated. In
this case, the hidden counter starts out at 0, discovers that L1[0] is
in L2, and removes it – reducing the length of L1 to 3. The counter
is then incremented to 1, and the code proceeds to check if the value
of L1[1] is in L2. Notice that this is not the original value of L1[1]
(i.e., 2), but rather the current value of L1[1] (i.e., 3). As we can see,
it is possible to figure out what happens when the list is modified
within the loop. However, it is not easy. And what happens is likely
to be unintentional, as in this example.
One way to avoid this kind of problem is to use slicing to clone –
(i.e., make a copy of) the list and write for e1 in L1[:]. Notice that
writing
newL1 = L1
for e1 in newL1:
would not solve the problem. It would not create a copy of L1, but
would merely introduce a new name for the existing list. Slicing is
not the only way to clone lists in Python. The expression list(L)
returns a copy of the list L. If the list to be copied contains mutable
objects that we want to copy as well, import the standard library
module copy and use the function copy.deepcopy.
3. Explain how to add, modify and delete elements from a
dictionary.
Creating a dictionary
A dictionary may contain any data type and is mutable. Its keys,
however, are immutable and can only be a string, tuple, or a number.
Values stored on a dictionary can only be accessed through the keys.
Syntax

117
dict = {} # To create an empty dictionary :
# To create a dictionary with key−value pairs :
dict = {keyl: valuel , key2:value2 , key3:value3 , key4:value4}
Where, dict is the dictionary name
key - User defined variable names
value – Values assigned for the key
Example 1.
member_1 = {'Name': 'MaduraiPublishers', 'price' :400, 'Telephone No.':0452-1234567}

Accessing Elements on a dictionary: A dictionary is an unordered


data type. Hence, we cannot use the indexing operator to access the
values. We will have to use the key to access the associated value.
To access data, we can either place the keys [] inside square brackets
or use the get() method.
Program 1.

# To access data by using keys:


>>>my_dict={'Name': 'Mary', 'Age' :24, 'Ranking': '5th'}
>>>my_dict['Name']
'Mary'
>>>my_dict['Ranking']
'5th'
Program 2.

# To access the same values with the get() method:


>>>my_dict = {'Name':'Mary', 'Average':89.5, 'Age': 24}
>>>my_dict.get('Name')
>>>my_dict.get('Average')

Output

'Mary'
89.5

Adding and Modifying Entries to a Dictionary


118
(a) Adding Dictionary Entries To add a new key-value pair or
modify the values of a dictionary, we will use the assignment (=)
operator. Python evaluates the new entry and checks if there
is a similar key in the current dictionary. If there is none, then
it appends the key:value pair. If the key already exists, then it
updates the value of the existing key.
Syntax
dict_name[key] = b
Where, b is the key-value pair to be added to the dict_name
dictionary
Program 3.
# To add a new key-value pair, status: regular: to the
already existing dictionary
>>>my_dict = {'Name': 'Mark', 'Age' : 24,
'Ranking' : '5th' ,'Average' :89.5}
>>>my_dict['status'] = 'regular'
>>>my_dict # To check the updated dictionary:
Output {'Name': 'Mark', 'status': 'regular', 'Ranking': '5
'Age': 24, 'Average': 89.5}
Note that the order of the key-value pair is not maintained for
allowing hashing within the dictionary class.
(b) Modifying Dictionary Entries To modify the current value,
use the assignment operator (=) to specify the new value to be
associated with the key.
Program 4.
# Modifying the value of Ranking from 5th to 3rd:
>>>my_dict = {'Name': 'Mary', 'Age' : 24, \
'Ranking' : '5th' ,,Average' :89.5}
>>>my_dict['Ranking'] = '3rd'
>>>my_dict

119
Output {'Ranking': '3rd', 'Name': 'Mary',
'Average': 89.5, 'Age': 24}
Removing or Deleting Elements from a Dictionary To remove
a key: value pair from a dictionary, we can use the pop() method
which removes the pair and returns the value of the given key.
(a) pop() method The pop() method is used to remove a specified
key-value pair from a dictionary and return the value of the
deleted key.
Example 2.
>>>my_dict = {'ocean' : 'Indian Ocean' , \
'Sea' : 'Arabian','river': 'Cauvery',\
'swamp':' Everglades'}
# To remove the key 'river' and its value:
>>>my_dict.pop('river')
>>>my_dict # Updated Dictionary
Output
'Cauvery'
{'Sea': 'Arabian', 'swamp': 'Everglades',
'ocean': 'Indian Ocean'}
(b) popitem() method The popitem() method is used to remove a
random key-value pair from a dictionary. The method does not
take any argument and returns the deleted key-value pair.
Program 5.
>>>my_dict {'ocean' : 'Indian Ocean' , 'Sea' : 'Arabian' ,
,'river' :'Cauvery', 'swamp':' Everglades'}
>>>my_dict.popitem()
('swamp', 'The Everglades')
# Here's what's left of my_dict:
>>>my_dict

120
Output
{'ocean': 'Indian Ocean', 'river': Cauvery,
'Sea': 'Arabian'}
(c) clear() method The clear() method is used to remove all key-value
pairs in a dictionary.
>>>my_dict.clear()
>>>my_dict
Output
{} # Empty Dictionary
(d) Deleting a Dictionary The del keyword is used to delete a
dictionary.
Syntax
del dict_name
Program 6.
# To delete the my_dict dictionary, we will use the del ke
>>> my_dict={'a':1,'b':2}
>>> my_dict
{'a': 1, 'b': 2}
>>> del my_dict
>>> my_dict
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
my_dict
NameError: name 'my_dict' is not defined
>>>
4. Write a program to sort an array of numbers using selection
sort.
def selectionSort ( alist ) :
counter = 0
for currentPosition in range(len(alist)−1, 0, −1):
maxValue = alist[ currentPosition ]
maxPosition = currentPosition

121
exChange = False
for index in range(0, currentPosition ) :
if alist [ index ] > alist [maxPosition]:
maxPosition = index
maxValue = alist[ index ]
alist [maxPosition], alist [ currentPosition ] = alist [ currentPosition ], alist [m

alist = [54, 26, 93, 17, 22, 31, 44, 5, 20]


selectionSort ( alist )
print( alist )

Listing 7: Python Program for Selection Sort


Output
[5, 17, 20, 22, 26, 31, 44, 54, 93]
>>>

5. Write the Python program for insertion sort


def insertionSort ( alist ) :
for index in range(1,len(alist)) :
keyvalue = alist [ index ]
position = index
while position > 0 and alist[ position − 1] > keyvalue:
alist [ position ] = alist [ position − 1]
position = position − 1
alist [ position ] = keyvalue
alist =[8,3,17,2,5,−7,1]
insertionSort ( alist )
print(' alist =', alist )

Listing 8: Python Program for Insertion Sort


Output
alist= [-7, 1, 2, 3, 5, 8, 17]
>>>
6. Define a Python Tuple. Explain some important operations
122
on tuples.
TUPLES
A tuple is an immutable sequence type that contains an ordered
collection of objects. It can store items of different types which are
indexed by integers and can hold as many items as needed.
(a) Creating a Tuple
To create a tuple, programmers will generally enclose tuple items
inside parentheses and separate them with comma. The parentheses
are however, optional and we can create a tuple without them.
They are often considered as read only lists.
Syntax
my_tuple = [] # To create an empty tuple
my_tuple = [item1 , item2 , ... itemn] # tuple of mixed items
mytuple_1 = (1, 3, 5, 7, 9, 11, 13) # Numeric
mytuple_3 = ("ruby", "gold", "diamond") # Strings
mytuple_2 = ("Python", 3.6, 2) # Mixed−type
# Python likewise allows the creation of a nested tuple :
mytuple_4 = ("collection", (10, 20, 30), [2, 4, 6])
To create a tuple with only one item, since this item will look like
a string place a comma after the item, to tell Python that it is a
tuple.
Program 1.
my_tuple5 = ("program",) # Tuple with only one item
my_tuple = () # To create an empty tuple we use Empty Parenthesis
# To create a tuple without the parentheses
numbers = 5, 3, 4, 0, 9

(b) Accessing Tuple Items


Indexing
The index operator indicates the index of the element to access.
The first element is an index zero. Accessing an item outside the
scope of the indexed elements will generate an IndexError. In

123
addition, accessing an index with a noninteger numeric type will
raise a NameError.
Syntax
my_tuple = [index] # To access tuple items
# Create new_tuple with strings as elements:
new_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'e')
>>>new_tuple[0] # To access the first element
'p'
>>> new_tuple[7] # To access the 7th element
'm'
>>>new tuple # To print the original list
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'e')
Negative Indexing It is a sequence type, we can access tuples
through negative indexing. The last "term takes the -1 index,
the penultimate item the -2 index, and so on.
>>>new_tuple[-l] # To access the last item
'e'
>>>new tuple[-7] # To access the -7th element
'g'

Table 14: Tuple Positional Index

Index# 0 1 2 3 4 5 6 7 8
String p r o g r a m m e
Negative -9 -8 -7 -6 -5 -4 -3 -2 -1
index

Slicing a Tuple
The slicing operator (:) is used to access a range of items in a tuple.
Syntax tuple_name [start : finish-l]
Where, tuple_name is the user-defined name for the string start
indicates the index of the initial character of the substring finish
indicates the index of the ending character of the substring

124
Program 2. # Create new_tuple with strings as elements:
>>> new_tuple = ('i','m','m','u','t','a','b','1','e')
# To access the elements on the 4th to the 6th index:
#4 is the index of the first item and 7 is the index of the
#first item to be excluded.
>>> new_tuple[4:7]
# To access tuple elements from index 2 to the end:
>>> new tuple[2:]
# To access tuple items from the beginning to the 3rd index:
>>> new_tuple[:4]

Output

('t', 'a', 'b')


('m', 'u', It', 'a', 'b', '1', 'e')
('i', 'm', 'm', 'u')
Program 3.
# Program for Accessing tuple items
tup1 =('physics ' , ' chemistry ' , 1997, 2000);
tup2 = (1,2,3,4,5,6,7) ;
print("tup1 [0]: ", tup1 [0]) # Indexing
print("tup2 [1:5]: ", tup2 [1:5]) # Slicing

Output

tupl[0]: physics
up2[1:5]: (2, 3, 4, 5)

Changing, Reassigning, and Deleting Tuples A tuple is immutable


so we cannot alter its elements. However, if it contains an element
which is a mutable data type, in such cases, we can modify the nested
items within the list element.
Example 1.
>>>my_tuple = ('a', 5, 3.5, [' P', 'y', 't', 'h', 'o', 'n'])
125
Replacing a Tuple To replace the item on index 2 of the list which
is on index 3 of my_tuple:
>>> my_tuple[3][2] = 'x'
>>> my_tuple
('a', 5, 3.5, ['P', 'y' , 'x' , 'h', 'o' , 'n'])
To replace or modify other data types, we can reassign a tuple to an
entirely different set of values or elements.
Reassigning a Tuple To reassign a tuple, list a different set of
elements and assign it to the tuple. >>> my_tuple = ('c', 'o', 'd', 'e
Deleting a Tuple To delete a tuple and all the items stored in it,
use the keyword del.
Syntax
del my_tuple
Program 4.
tup1 = (12, 34.56); # Creating and Updating a tuple
tup2 = ('abc' , 'xyz' )
tup3 = tup1 + tup2
print(tup3)
# Deleting a tuple from the list
tup = (' physics ' , ' chemistry ' , 1997, 2000)
del tup
print("After deleting tup ")
print(tup)

Output
(12, 34.56, 'abc', 'xyz')
After deleting tup
Traceback (most recent call last):
File "/test1.py", line 9, in <module>
print(tup)
NameError: name 'tup' is not defined
>>>
126
Tuple Membership Test To test if a tuple contains a specific item,
we can use the membership operators in and not in.
Example 2.

>>>tuple_1 = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'e')
>>>'g' in tuple_1
>>>'1' in tuple_1
>>>'e' not in tuple_1
>>>'x' not in' tuple_1

Output

True
False
False
True

Tuple Methods
In Python, count() and index() are the two methods that work
with tuples.
(a) Count(x)
The count() returns the number of elements which is equal to the
given element. Syntax
mytuple.count('character')

Program 5.
>>>new tuple = ("p","r","a","g","r","a","m","m","e","r")
>>>new_tuple.count('m')
>>>new_tuple.count('r')
Output
2
3
127
(b) Index(x)
It returns the index of the first element which is equal to the
given element.
Syntax
mytuple.index('character')

Program 6.
>>>new tuple = ("p","r","o","g","r","a","m","m","e","r")
>>>new_tuple.index('m')
>>>new_tuple.index('r')
Output
6
1
Built-in Functions with Tuples
Several built-in functions are often used with tuple to carry out
specific tasks. Here are the functions that we can use with a
tuple.
len()
It returns the number of elements on a tuple.
>>> tuple_one = ('cat','dog','lion','elephant','zebra')
>>> len(tuple_one)
Output
5
(c) max()
It returns the largest element on a tuple.
>>>numbers_tuple = (1, 5, 7, 9, 10, 12)
>>>max(numbers_tuple)
Output
12
When a tuple holds items of purely string data type, max()

128
evaluates the items alphabetically and returns the alphabetically
largest item.
>>>my tuple = ('car','zebra','book','hat','shop','art')
>>>max(my_tuple)
Output
'zebra'
Using max() on tuples with mixed data types (string and numbers)
will raise a TypeError due to the use of unorderable types.
(d) min()
It returns the smallest element on a tuple.
>>>numbers_tuple = (1, 5, 7, 9, 10, 12)
>>>min(numbers_tuple)
Output
1
When used on a tuple that contains purely string data type min()
evaluates the items alphabetically and returns the alphabetically
first item.
>>>my_tuple = ('car','zebra','book','hat','shop','art')
>>>min(my_tuple)
Output 'art'

(e) sorted()
It returns a sorted list but it does not sort the tuple itself. The
order of elements inside the tuple remains unchanged.
>>>my_tuple = ('dog','bird','ant','cat','elephant')
>>>sorted(my_tuple)
# The order of elements inside the my_tuple however,
#remains the same
>>>my_tuple
Output

129
['ant', 'bird', 'cat', 'dog', 'elephant']
('dog', 'bird', 'ant', 'cat', 'elephant')
(f) sum()
It returns the total of all items on a tuple.
Example 3.
>>>my_tuple = (5, 10, 15, 20, 25, 30)
>>>sum(my_tuple)
Output
105

(g) tuple()
It converts iterables like string, list, dictionary, or set to a tuple.
How to convert a string to a tuple
>>>tuple("Programmer")
Output
('P', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'e', 'r')

Example 4.
>>>my_string = ("Hello World")
>>>tuple(my_string)
Output
('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd')
Converting a dictionary to a tuple
Example 5.
>>>tuple({'Name' :'Joshua', 'Animal':' elephant', 'Color': 'blue', 'Age': 22})

Output
('Age', 'Color', 'Name', 'Animal')
Example 6.
my_dict = {'Name' : 'Joy', 'Area':' Madurai' , 'subscription' : 'premium' }
>>>tuple(my_dict)

130
Output
('Name', 'Area', 'subscription')
Converting a list to a tuple
Example 7.
>>>tuple(['red', 'blue', 'yellow', 'green', 'orange', 'violet'])

Output
('red', 'blue', 'yellow', 'green', 'orange', 'violet')

Example 8.
>>>my_list = ['interest','rate','principal','discount','rollover']
>>>tuple(my_list)

Output
('interest', 'rate', 'principal', 'discount', 'rollover')

(h) Enumerate()
It returns an enumerate object containing the value and index of
all tuple elements as pairs
Example 9.
>>>my_tuple = (1, 3, 5, 7, 9, 11, 13, 15)
>>>enumerate(my tuple)
Output <enumerate object at 0x105bbb410>

7. Illustrate the ways of creating the tuple and the tuple assignment
with suitable programs
Relevant points from Question Number 6
8. Illustrate List Comprehension with suitable examples
We can create a 3 × 3 matrix using lists as shown below:
>>> M=[[1,2,3],[4,5,6],[7,8,9]]
>>> M
[[1,2,3],[4,5,6],[7,8,9]]

131
Here, we?ve coded a list that contains three other lists. The effect
is to represent a 3 × 3 matrix of numbers. Such a structure can be
accessed in a variety of ways: >>> M[1]. #get row 2
[4,5,6] #get row 2 and then item 3

9. Explain how to create a dictionary using tuples in Python.


First, we can show how two tuples can be combined together to form a
dictionary. This can be performed using the dictionary comprehension
in which we can iterate through the key and value tuple simultaneously
using enumerate() and construct the desired dictionary.
Program 1.
# initializing tuples
test_tup1 = ('KLN', ' is ' , ' best ' )
test_tup2 = (1, 2, 3)
# printing original tuples
print("The original key tuple is : " + str(test_tup1))
print("The original value tuple is : " + str(test_tup2))
# Using Dictionary Comprehension
# Convert Tuples to Dictionary
res = {test_tup1[i] : test_tup2[i ] for i , _ in enumerate(test_tup2)}
# printing result
print("Dictionary from tuples : " + str(res))

Listing 9: Convert Tuples to Dictionary Using Dictionary


Comprehension

Output

The original key tuple is : ('KLN', 'is', 'best')


The original value tuple is : (1, 2, 3)
Dictionary from tuples : {'KLN': 1, 'is': 2, 'best': 3}
>>>

Program 2.

132
# initializing tuples
test_tup1 = ('KLN', ' is ' , ' best ' )
test_tup2 = (1, 2, 3)

# printing original tuples


print("The original key tuple is : " + str(test_tup1))
print("The original value tuple is : " + str(test_tup2))

# Using zip() + dict()


# Convert Tuples to Dictionary
res = dict(zip(test_tup1, test_tup2))

# printing result
print("Dictionary from tuples : " + str(res))

Listing 10: Convert Tuples to Dictionary using zip function

Output

The original key tuple is : ('KLN', 'is', 'best')


The original value tuple is : (1, 2, 3)
Dictionary from tuples : {'KLN': 1, 'is': 2, 'best': 3}
>>>

10. Explain how to pick a random item from a range in list or


tuple.
11. Write a program to sort an array of numbers using merge
sort.
12. Write a Python program to create a histogram from a given
list of integers.

133

You might also like