Python (Punithavathi)
Python (Punithavathi)
1.1 ALGORITHM
Algorithm is defined as a step by step procedure for solving any problem.
An algorithm is a sequence of finite instructions, often used for calculation and data
processing.
Example:
Algorithm for Calculating Area of the Circle
(1) Start
(2) Read the value of radius r
(3) Calculate Area=3.14*r*r
(4) Print the Area of the circle
(5) Stop
Process 1
Process 1
Process n
True If False
A> B
An iterator is an object that implements next, which is expected to return the next element
of the iterable object that returned it, and raise a Stop Iteration exception when no more elements
are available. The iteration structure is shown in figure 1.3.
True
Condition False
Check
Conditional
code
1.3 NOTATIONS
1.3.1 Pseudocodes – Introduction
Pseudocode is a kind of structural english for designing algorithm. Pseudocodes came from
two words. Pseudo and code "pseudo" means imitation and "code" refer to instructions, written in
a programming language.
1.4 Problem Solving and Python Programming
Pseudocode neither be compiled nor executed, and there are no real formatting or syntax
rules. The benefit of pseudo code is that it enables the programmer to concentrate on the algorithms
without worrying about all the syntactic details of a particular programming language.
Example
A pseudocode to add two numbers and display the results:
READ num1, num2
result = num1 + num2
WRITE result
In the example above, READ and WRITE are in capital letters. Following are few keywords
we use
Sequence : It keeps the statement that are “stacked” in sequence all starting in the same
column.
Selection : It indent the statements that fall inside the selection structure, but not the
keywords that form the selection.
Looping : It indent the statements that fall inside the loop, but not the keywords that form
the loop.
Algorithmic Problem Solving 1.5
Example
ENDIF for IF statement
1.4 FLOWCHART
Introduction
A flow chart is a diagrammatic representation, that illustrates the sequence of operations to
be performed to arrive at the solution. Each step in the process is represented by a different symbol
and contains a short description of the process step. The flow chart symbols are linked together with
arrows showing the flow direction of the process.
Flowchart is very helpful in writing programs and explaining them to others. Flowchart
makes us to understand the problem unambiguously. It is often used by the programmer as a program
planning tool for organizing a sequence of steps necessary to solve a problem by a computer.
(e) Only one flow line should enter a decision symbol, but two or three flow lines, one for
each possible answer, can leave the decision symbol.
=0 =0
(f) Only one flow line is used in conjunction with terminal symbol.
Start Stop
Algorithmic Problem Solving 1.7
(g) Write briefly within the standard symbols. If necessary, you can use the annotation sym-
bol to describe data or computational steps more clearly.
Calculation Part
(h) If the flowchart becomes complex, it is better to use connector symbols to reduce the
number of flow lines. Avoid the intersection of flow lines if you want to make it more
effective and better way of communication.
(i) Ensure that the flowchart has a logical start and stop.
(j) Validity of the flowchart can be tested by passing through it with a simple test data.
Display sum
Stop
1.8 Problem Solving and Python Programming
{
max = x;
}
else
{
max = y;
}
.....
}
One statement in a high level programming language is usually translated into multiple
machine instruction that achieve the effect specified by the statement.
Decide on:
Computational means,
exact vs. approximate
solving, algorithm design technique
Design an algorithm
Prove correctness
Analyzing an Algorithm
Sequential algorithms: Instructions are executed one after the other, one operation at a
time. Accordingly, algorithms designed to be executed on such machines.
Parallel algorithms: The central assumption of the RAM model does not hold for some
newer computers that can execute operations concurrently, i.e., in parallel.
First, they provide guidance for designing algorithms for new problems, i.e., problems for
which there is no known satisfactory algorithm. Second, algorithms are the cornerstone of computer
science. Every science is interested in classifying its principal subject, and computer science is
no exception. Algorithm design techniques make it possible to classify algorithms according to
an underlying design idea; therefore, they can serve as a natural way to both categorize and study
algorithms.
These are the two options that are most widely used nowadays for specifying algorithms.
In the earlier days of computing, the dominant vehicle for specifying algorithms was a
flowchart, a method of expressing an algorithm by a collection of connected geometric shapes
containing descriptions of the algorithm’s steps. This representation technique has proved to be
inconvenient for all except very simple algorithms.
Time efficiency, indicating how fast the algorithm runs Space efficiency, indicating how
much extra memory it uses.
If one is not satisfied with the algorithm’s efficiency, simplicity, or generality, one must
return to the drawing board and redesign the algorithm. In fact, even if one’s evaluation is positive,
it is still worth searching for other algorithmic solutions.
Example 1:
Sum of two numbers.
Algorithm
Step 1 : Start
Step 2 : Input the value of A and B.
Step 3 : Find the sum of A and B.
sum=A+B
Step 4 : Print the value of sum
Step 5 : Stop.
Pseudocode
READ the value of variables A and B.
Find the sum.
sum = A + B.
WRITE the output of sum.
STOP
Algorithmic Problem Solving 1.13
Flowchart
Start
Read A, B
Sum = A + B
Print sum
Stop
Example 2:
Find the area and circumference of circle.
Algorithm
Step 1 : Start
Step 2 : Input the radius of the circle
Step 3 : Find the area and circumference using the formula
Area = 3.14 * r *r
Circumference = 2*3.14*r
Step 4 : Print the area and circumference of the circle.
Step 5 : Stop
Flowchart
Start
Calculate
area = 3.14*r*r
Circumference = 2*3.14*r
Stop
1.14 Problem Solving and Python Programming
Pseudo code
READ the radius of the circle
Find the area and circumference of the circle using the formula
Area = 3.14*r*r
Circumference = 2*3.14*r
WRITE the Output of area and Circumference of the circle
Stop
Example 3:
Find the greatest of 3 numbers.
Algorithm
Step 1 : Start
Step 2 : Read the value of a, b, c
Step 3 : Compare the values of a,b and c.
Step 4 : If a is greater than b, compare a with c.
If a is greater than c then print a is big.
Step 5 : If a is not greater than b & c then compare b and c.
Step 6: If b is greater than c print b is big else print C is big.
Step 7 : Stop
Pseudocode :
READ the values of a, b, c
IF (a > b) && (a > c) THEN
WRITE a is big
ELSE
IF (b>c) THEN
WRITE b is big
ELSE
WRITE c is big
ENDIF
ENDIF
Stop
Algorithmic Problem Solving 1.15
Flowchart
Start
Read A, B
If No
Yes
(a>b) &&(a>c)
If No
Print a in big Yes
(b > c)
Stop
Example 4:
Check whether the given number is even or odd.
Algorithm
Step 1 : Start
Step 3 : If (n%2==0) then print it is an even number, else print it is an odd number
Step 4 :Stop
Pseudocode
READ the value of n
IF (n%2==0) THEN
WRITE n is even number
ELSE
WRITE n is odd number
ENDIF
Stop
1.16 Problem Solving and Python Programming
Flowchart
Start
Read n
If No
(n%2==0)
Yes
Print n in even Print n in odd
Stop
Example 5:
Find the factorial of a given number.
Algorithm
Step 1 : Start
Step 2 : Initialize r=0, sum=0
Step 3 : READ the value of n
Step 4 : If n>0 do the following else goto step 6
Step 4.1: r=n mod 10
Step 4.2 : sum=sum*10+r
Step 4.3 : n=n div 10
Step 5 : Goto step 4
Step 6 : Print sum
Step 7 : Stop
Pseudocode
Set initial sum=0, r=0
READ the value of n
WHILE (n>0)
r=n%10
sum=sum*10+r
Algorithmic Problem Solving 1.17
n=n/10
ENDWHILE
Repeat while until the condition fail
WRITE the sum
Stop
Flowchart:
Start
Initialize
r=0; sum =0
Yes While No
n>0
r=n%10
sum=sum*10+r
n=n/10
Print sum
Stop
In simple terms, an iterative function is one that loops to repeat some part of the code, and
a recursive function is one that calls itself again to repeat the code.
Using a simple for loop to display the numbers from one to ten is an iterative process.
Solving the Eight Queens Problem is a simple recursive process.
Recursion is a problem solving approach by which a function calls itself repeatedly until
some specified condition has been satisfied. Recursion splits a problem into one or more simpler
versions of itself.
1.18 Problem Solving and Python Programming
Illustrative problems:
Find minimum number in a list
Program
lst = []
num = int(input('How many numbers: '))
for n in range(num):
numbers = int(input('Enter number '))
lst.append(numbers)
print("Maximum element in the list is :", max(lst), "\n Minimum element in the list is :",
min(lst))
Output :
Algorithmic Problem Solving 1.19
Output:
[17, 20, 26, 31, 44, 54, 55, 77, 93]
Program:
def TowerOfHanoi(n , from_rod, to_rod, aux_rod):
if n == 1:
print "Move disk 1 from rod",from_rod,"to rod",to_rod
return
TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)
print "Move disk",n,"from rod",from_rod,"to rod",to_rod
TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)
Output:
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Algorithmic Problem Solving 1.21
In interactive mode, type Python programs and the interpreter displays the result.
Compiler
A compiler reads the program and translates it completely to machine readable form called
object code or executable code before the program starts running. Once a program in compiled, the
program can be executed repeatedly without further translations. The figure 2.2 shows the structure
of a compiler.
>>>1+1
2
Interactive Mode
So far we have run Python in interactive mode, which means that one interact directly with
the interpreter. Interactive mode is a good way to get started, but if one is working with more than
a few lines of code, it can be clumsy.
The alternative is to save code in a file called a script and then run the interpreter in script
mode to execute the script.
Example:
# first simple program
It prints Hello, World. In python printing statement uses the keyword print as in the above
mentioned format.
The parenthesis indicates that the print is a function. The single quotation represents the
beginning and end of the text to be displayed.
The values belong to different data types. In Python, the standard data types available are:
(1) Numbers
(2) String
(3) List
(4) Tuple
(5) Dictionary
Example:
print True # True is a Boolean value print False # False is a Boolean value.
>>>True and False # False
>>>False or True # True
>>> (30 > 45) or (27 < 30) # True
>>> not True # False
>>> not (3 > 4) # True
>>> 3 > 4 # False
>>> test = (3 > 4)
>>> test # False
>>> type(test) #<type ‘bool’>
The substring access is possible through the slicing operator ([] or [:]). The string index 0
represents beginning of the string whereas, index -1 represents ending of the string. The following
examples illustrate the string and substring accesses.
2.4 Problem Solving and Python Programming
Example:
#str – string variable (explained later in this chapter) assigned with a value
str= ‘Hello, World!’
Example:
list1=[‘abcd’, 345, 3.2,’python’, 3.14]
list2=[234, ‘xyz’]
Example:
tuple1= (‘abcd’, 345 , 3.2,’python’, 3.14)
print tuple1[2:] #prints tuple1 starting at index 2 till the (3.2, ‘python’, 3.14)
end
print tuple 2 * 2 # asterisk (*) -is the repetition operator. (234, 'xyz', 234, 'xyz')
Prints the tuple2 two times.
print tuple1 + # prints concatenated tuples (‘abcd’, 345, 3.2,’python’,
tuple2 3.14, 234, ‘xyz’)
2.4 VARIABLE
Variable is an identifier that refers to a value. While creating a variable, memory space is
reserved in memory. Based on the data type of a variable, the interpreter allocates memory. The
assignment statements are used to create new variables and assign values to them.
>>>msg= ‘ Hello, World!’
>>> n=12
>>> pi=3.14
The first statement creates a variable, msg and assigns ‘Hello, World!’ to it. The second
statement creates the variable, n assigns 12 to it. The third statement creates the variable, pi and
assigns the value 3.14.
Variable names can contain both letters and numbers, but they do not start with a number.
The underscore character ( _ ) can be used in variable names . In addition to variables, Python has
31 keywords.
Python Identifiers
Identifier is the name given to entities like class, functions, variables etc. in Python. It helps
differentiating one entity from another.
(2) An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
(3) Keywords cannot be used as identifiers.
(4) We cannot use special symbols like !, @, #, $, % etc. in our identifier.
(5) Identifier can be of any length.
Example:
17 #expression
X #expression
X+17 #expression
A statement is a code that ends with a new line. So far, we have seen two kinds of statements:
print and assignment. Python allows the use of line continuation character (\) to denote that the
line should continue.
Example:
Total = mark1+ \
mark2+ \
mark3
But the statements contained within [], {} or () brackets do not need to use line continuation
characters. For example,
For example,
5,28 are of type int.
3.76 is float
“Hai” is of type string.
For example,
>>> a, b, c = 2, 4, 6, “Hai”
If all the variables possess same value, then it can be represented as follows:
>>>a=b=c = “5”
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to one's choice , but it must be consistent throughout
that block.
Generally four whitespaces are used for indentation and is preferred over tabs. Here is an
example.
2.6 OPERATORS
An operator is a special symbol that asks the compiler to perform particular mathematical
or logical computations like addition, multiplication, comparison and so on. The values that are
applied to the operator are called operants. For eg, in the expression 4 + 5, 4 and 5 are operands
and + is an operator.
Arithmetic Operators
Operator Description
+ Addition Adds two operands.
- Subtraction Subtracts second operand from first operand.
* Multiplication Multiplies two operands.
/ Division Divides first operand by second operand.
% Modulus Divides first operand by second operand and returns the remainder
** Exponent Performs exponential (power) calculation
// Floor Division Division of operands in which the quotient without fraction is returned
(Integer Division) as a result.
Sample Code:
a = 21
b = 10
c=0
c=a+b
print “Result of addition “, c
c=a-b
print “Result of subtraction “, c
c=a*b
print “Result of multiplication “, c
c=a/b
2.10 Problem Solving and Python Programming
Sample Output:
Result of addition 31
Result of subtraction 11
Result of multiplication 210
Result of division 2
Result of modulus 1
Result of exponentiation 8
Result of floor division 2
Assignment Operators
Operator Description
= Assigns values from right side operand to left side operand.
+= Performs addition using two operands and assigns the result to left side
operand.
-= Subtracts right side operand from the left side operand and assigns the
result to left side operand.
*= Performs multiplication using two operands and assigns the result to left
side operand.
/= Divides left side operand by the right side operand and assigns the result to
left side operand.
%= Finds modulus using two operands and assigns the result to left side operand.
**= Performs exponential calculation and assigns the result to the left side
operand.
//= Performs floor division and assigns the result to the left side operand
Sample Code:
a = 10
b=5
c=a
print “c is “,c
c=a+b
print “c is “, c
c += a # c=c+a
2.12 Problem Solving and Python Programming
print “c is “, c
c -=a # c=c-a
print “c is “, c
c *= a # c=c*a
print “c is “, c
c /= a # c=c/a
print “c is “, c
c =2
c %= a # c=c%a
print “c is “, c
c **= a # c = c ** a
print “c is “, c
c //= a # c = c // a
print “c is “, c
Sample Output:
c is 10
c is 15
c is 25
c is 15
c is 150
c is 15
c is 2
c is 1024
c is 102
Logical Operators
Following table shows all the logical operators supported by Python:
Operator Description
and Logical AND returns true, if and only if both operands are true.
or Logical OR returns true, if any of the two operands is true.
not Logical NOT returns the logical negation of its operand.
Here, any nonzero number is interpreted as true and zero is interpreted as false. Both the
and operator and the or operator expect two operands. not operator operates on a single operand.
The behaviour of each logical operator is specified in a truth table for that operator.
Data, Expressions, Statements 2.13
Sample Code:
a=True
b=False
print a and b
print a or b
print not a
Sample Output:
False
True
False
Bitwise Operators
Bitwise operators perform bit by bit operations and explained as:
Operator Description
& Performs Bitwise AND operation between two the operands.
| Performs Bitwise OR operation between two the operands.
^ Performs Bitwise XOR (exclusive OR) operation between two the operands.
~ Performs Bitwise 1’s complement on a single operand.
<< Shifts the first operand left by the number of bits specified by the second operand
(Bitwise Left Shift).
>> Shifts the first operand right by the number of bits specified by the second operand
(Bitwise Right Shift).
Sample Code:
a = 60 # 60 = 0011 1100
b = 26 # 13 = 0001 1010
c = a & b; # 24 = 0001 1000
print “Result of Bitwise AND is “, c
c = a | b; # 62 = 0011 1110
print “Result of Bitwise OR is “, c
c = a ^ b; # 38 = 0010 0110
print “Result of Bitwise XOR is “, c
c = ~a; # -61 = 1100 0011
print “Result of Bitwise Ones Complement is “, c
c = a << 2; # 240 = 1111 0000
print “Result of Bitwise Left Shift is “, c
c = a >> 2; # 15 = 0000 1111
print “Result of Bitwise Right Shift is “, c
2.14 Problem Solving and Python Programming
Sample Output:
Result of Bitwise AND is 24
Result of Bitwise OR is 62
Result of Bitwise XOR is 38
Result of Bitwise Ones Complement is -61
Result of Bitwise Left Shift is 240
Result of Bitwise Right Shift is 15
Membership Operators
Membership operators test for membership in a sequence, such as strings, lists, or tuples
and explained as:
Operator Description
in Evaluates to true if it finds a variable in the specified sequence and false otherwise.
not in Evaluates to true if it does not find a variable in the specified sequence and false
otherwise.
Sample Code:
a=6
b=2
list = [1, 2, 3, 4, 5 ];
print a in list
print a not in list
print b in list
print b not in list
Sample Output:
False
True
True
False
Identity Operators
Identity operators compare the memory locations of two objects. They are explained below:
Operator Description
is Returns true if both operands point to the same object and false otherwise.
is not Returns false if both operands point to the same object and true otherwise.
Data, Expressions, Statements 2.15
Sample Code:
a = 20
b = 20
print a is b
print id(a) == id(b)
print a is not b
b=30
print a is b
print a is not b
print id(a) == id(b)
Sample Output:
True
True
False
False
True
False
Operator Description
+ Returns its numeric argument without any change.
- Returns its numeric argument with its sign changed.
Sample Code:
a = 10
b = +a
print b
c = -a
print c
Sample Output:
10
–10
2.16 Problem Solving and Python Programming
The following table summarizes the operator precedence in Python, from the highest
precedence to the lowest precedence. Operators in the same box have the same precedence and
group from left to right (except for comparisons statements).
Examples:
4 * (6-3) is 12, and (1+2)**(6-3) is 27.
3**1+1 is 4, not 9.
2*1**4 is 2, not 16.
4*6-2 is 22, not 16.
4+2/2 is 5, not 3.
4/2*2 is 4, not 1.
2.7 COMMENTS
Comments are the non-executable statements explain what the program does. For large
programs it often difficult to understand what it does. The comment can be added in the program
code with the symbol #.
Example:
print ‘Hello, World!’ # print the message Hello, World!; comment
v=5 # creates the variable v and assign the value 5; comment
Example:
print() Print objects to the stream.
Reads a line from input, converts it to a string (stripping a trailing newline), and
input()
returns that.
abs() Return the absolute value of a number.
len() Return the length (the number of items) of an object.
Sample Input/Output:
p
>>> tuple(‘Mary’)
(‘M’, ‘a’, ‘r’, ‘y’)
tuple() string, list → tuple
>>> tuple([1,2,3,4]) # [ ] for list, ( ) for tuple
(1, 2, 3, 4)
>>> age = 21
>>> sign = ‘You must be ‘ + age + ‘Years old’
Many Python functions are sensitive to the type of data. For example, you cannot concatenate
a string with an integer. If you try, it will result in following error.
For the example above, use the str() conversion function to convert integer to string data
type.
>>> age = 21
>>> sign = “You must be “ + str(age) + “Years old”
>>>sign
Sample Output:
You must be 21 Years old
Math functions
Math and cmath are mathematical modules available in Python to support familiar
mathematical functions. A module is a file that contains a collection of related functions. Before
using built-in math functions, import math module.
>>>import math
It will create a module object named math which contains functions and variables defined in
the module. Some of the familiar math functions are listed in the table below.
1.0
factorial(n) Return n factorial math.factorial(5) 120
gcd(n,m) Return greatest math.gcd(10,125) 5
common divisior of
(n,m)
trunc(x) Return the real math.trunc(1.999) 1
value x truncated to
an integral
sin(x), cos(x), Return the arc sine, math.sin(math.pi/4) 0.7071067811865476
tan(x) cosine, tangent of x, math.cos(math.pi) –1.0
in radians.
math.tan(math.pi/6) 0.5773502691896257
Mathematical Constants
•• math.pi
The mathematical constant π = 3.141592..., to available precision.
•• math.e
The mathematical constant e = 2.718281..., to available precision.
Syntax:
def function_name( parameters ):
“function_docstring”
2.22 Problem Solving and Python Programming
function_suite
return [expression]
The code block within every function starts with a colon (:) and is indented. The first
statement of a function can be an optional statement - the documentation string of the function or
docstring. The statement return [expression] exits a function, and optionally it returns the result of
the function. The rules for function names are the same as for variable names: letters, numbers and
some punctuation marks are legal, but the first character can’t be a number. Keywords should not be
used as function name. To avoid confusion, use different names for functions and variables.
Syntax:
function_name(parameters)
Function to display Welcome message.
def display():
print “Welcome!!!”
>>>display()
Sample output:
Welcome!!!
The first line of the function definition is called the header; the rest is called the body. The
header has to end with a colon and the body has to be indented. By convention, the indentation is
always four spaces. In this example, the function name is display().The empty parentheses after the
name indicate that this function doesn’t take any arguments.
Sample Input/Output:
Enter first number 10
Enter second number 5
Enter third number 25
25 is bigger
In this example, the function name is great().It takes three parameters and return the greatest
of three. input() reads input value from the user. The function is invoked by calling great(n1,n2,n3).
print() displays the output. The strings in the print statements are enclosed in double quotes.
Sample output:
3.141592653589793
Sample output:
Enter Radius:6
Area of Circle:113.04
Sample input/output:
Enter a number:5
120
2.26 Problem Solving and Python Programming
Sample input/output:
Enter first number1
Enter second number11
Before Swap: n1= 1 n2= 11
After Swap: n1= 11 n2= 1
Sample input/output:
Enter a year1900
Not a Leap Year
Data, Expressions, Statements 2.27
2.11.3 Python program to test for leap year using calendar module
Python provides this functionality already in the library module ‘calendar’.
import calendar
def leapyr(yr):
if(calendar.isleap(yr)): # Using built-in function to check for leap year
print ‘Leap Year’
else:
print ‘Not a Leap Year’
return
year=input(“Enter a year”)
leapyr(year)
Sample output:
15
Sample output:
Reverse String:nohtyP
2.28 Problem Solving and Python Programming
Sample input/output:
Enter a no. 10
No. is not between 1 and 10
Enter a no. 4
No. is between 1 and 10
2.11.7 Python program to print the even numbers from a given list
def print_even(l): # l represents list of values
for n in l:
if n % 2 == 0:
print ‘\n’, n
return
print_even([1, 2, 3, 4, 5, 6, 7, 8, 9])
Sample output:
2
4
6
8
2.11.8 Function that circulates/rotates the list values for given number of times (order)
def rotate(l,order):
for i in range(0,order):
j=len(l)-1
Data, Expressions, Statements 2.29
while j>0:
tmp=l[j]
l[j]=l[j-1]
l[j-1]=tmp
j=j-1
print i, ‘rotation ’,l
return
l=[1,2,3,4,5]
rotate(l,3)
Sample output:
0 rotation: [5, 1, 2, 3, 4]
1 rotation: [4, 5, 1, 2, 3]
2 rotation: [3, 4, 5, 1, 2]
2.11.9 Find the distance between two points (xc,yc) and (xp,yp).
import math
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result
xc=int(input("Enter xc"))
yc=int(input("Enter yc"))
xp=int(input("Enter xp"))
yp=int(input("Enter yp"))
print (distance(xc,yc,xp,yp))
Sample input/output:
Enter xc 2
Enter yc 2
Enter xp 4
Enter yp 4
2.82
2.30 Problem Solving and Python Programming
no=input(“Enter a number”)
sum=perfect_number(no) # function call
if(sum==no):
print ‘Perfect number’
else:
print ‘Not a Perfect number’
Sample input/output:
Enter a number5
Not a Perfect number
Enter a number6
Perfect number
Sample input/output:
Enter a string:madam
madam is a Palindrome
q=no
rev = 0
while(q!=0): # loop for reverse
rev = q % 10 + rev * 10
q = q / 10
if( rev == no):
print(‘%d is a palindrome number’ %no)
else:
print(‘%d is not a palindrome number’ %no)
Sample input/output:
Enter a Number121
121 is a palindrome number
UNIT – 3
CONTROL FLOW
True and False are special values that belong to the type bool; they are not strings:
type(True)
<class 'bool'>
The == operator is one of the relational operators; the others are given in the following table:
x != y x is not equal to y
x >y x is greater than y
x <y x is less than y
x>=y x is greater than or equal to y
X<=y x is less than or equal to y
Although these operations are probably familiar to you, the Python symbols are different
from the mathematical symbols. A common error is to use a single equal sign (=) instead of a double
equal sign (==). Remember that = is an assignment operator and == is a relational operator. There
is no such thing as =< or =>.
3.2 OPERATORS
Operators are the constructs (operator) which can manipulate the value of operands.
Types of Operators
Python language supports the following types of operators.
(i) Arithmetic Operators
(ii) Comparison (Relational) Operators
(iii) Assignment Operators
(iv) Logical Operators
(v) Bitwise Operators
(vi) Membership Operators
(vii) Identity Operators
Example
Operation Meaning Description
(a=10, b=20)
+ Addition Adds values on both side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left a – b = -10
hand operand
* Multiplication Multiplies values on both side of the a * b = 200
operator
/ Division Divides left hand operand by right hand b/a=2
operand
% Modulus Divides left hand operand by right hand b%a=0
operand and returns remainder
** Exponent Performs exponential (power) a**b =10 to the power 20
calculation on operators.
// Floor Division The division that results into whole 9//2 = 4 and 9.0//2.0 = 4.0,
number adjusted to the left in the number -11//3 = -4, -11.0//3 =-4.0
live.
Example 1 :
(1) Integer arithmetic
days = int(input(“Enter days: “))
months = days / 30
days = days % 30
Control Flow 3.3
Output:
Enter days: 265
Months = 8 Days = 25
Example 2 :
days = int(input(“Enter days: “))
print(“Months = %d Days = %d” % (divmod(days, 30)))
The divmod(num1, num2) function returns two values , first is thedivision of num1 and
num2 and in second the modulo of num1 and num2.
Example
Operation Meaning Description
(a=10, b=20)
== Equal to If the values of two operands are equal, (a == b) is not true.
then the condition becomes true.
!= Not equal If the values of two operands are not equal, a – b = -10
then the condition becomes true.
> Greater than If the value of left operand is greater than (a > b) is not true
the value of the operand, then the condition
becomes true.
< Less than If the value of left operand is less than the (a < b) is not true
value of the operand, then the condition
becomes true
>= Greater than or If the value of left operand is greater than or (a >= b) is not true
Equal to equal to the value of right operand, then
the condition becomes true
<= less than or If the value of left operand is less than or (a <= b) is not true
Equal to equal to the value of right operand, then
the condition becomes true
Example:
>>> 1<2
True
>>> 3 > 34
False
>>> 23 == 45
3.4 Problem Solving and Python Programming
False
>>> 34 != 323
True
Example:
a = 0011 1100
b = 0000 1101
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Example
Operation Meaning Description
(a=10, b=20)
& Binary AND Operator copies a bit to the result (a & b) = 12
if it exists in both operands (means 0000 1100)
| Binary OR It copies a bit if it exists in either (a | b) = 61
operand. (means 0011 1101)
^ Binary XOR It copies the bit if it is set in one (a ^ b) = 49
operand but not both. (means 0011 0001)
~ Binary Ones It is unary and has the effect of (~a ) = -61
Complement ‘flipping’ bits. (means 1100 0011 in 2’s
complement form due to
a signed binary number.
<< Binary Left Shift The left operand value is moved a << = 240
left by the number of bits (means 1111 0000)
specified by the right operand.
>> Binary Right Shift The left operand value is moved a >> = 15
right by the number of bits (means 0000 1111)
specified by the right operand.
Description Example
is Evaluates to true if the variables on either x is y, here is results in 1 if id(x) equals
side of the operator point to the same id(y).
object and false otherwise.
is not Evaluates to false if the variables on x not in y, here not in results in a 1 if x is
either side of the operator point to the not a member of sequence y.
same object and true otherwise. x is not
y, here is not results in 1 if id(x) is not
equal to id(y).
The following table lists all operators from highest precedence to lowest.
Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus (method names for the last two are
+@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>><< Right and left bitwise shift
& Bitwise ‘AND’
^| Bitwise exclusive ‘OR’ and regular ‘OR’
<= <>>= Comparison operators
Equality operators
= %= /= //= Assignment operators
-= += *= **=
is not Identity operators
Control Flow 3.7
This technique is some what different from normal program. The sequence of the control
flow may differ from normal logical code. Decision structures evaluate multiple expressions which
produce TRUE or FALSE as outcome. The programmer to determine which action to take and
which statements to execute if outcome is TRUE or FALSE otherwise.
3.4.1 i) If Statement
It is similar to that of other languages. The if statement contains a logical expression using
data which is compared and a decision is made based on the result of the comparison.
Syntax
if expression:
statement(s)
Flowchart
False
Test
expression
True
Statement(s)
Example:
a=10
if a>9:
print(“A is Greater than 9”)
Output
A is Greater than 9
The else statement is an optional statement and there could be at most only one else statement
following if.
Syntax
if expression:
statement(s)
else:
statement(s)
Flowchart
If Test False
expression
True
Example 1:
a=10
b=20
if a>b:
Control Flow 3.9
Output
B is Greater than A
Example 2:
num=3
#num= -5
#num=0
If num>=0:
Print(“Positive or Zero”)
else:
Print(“Negative number”)
Output
Positive or Zero
In the above example. When num is equal to 3, the test expression is true and body of if is
executed and body of else is skipped.
If num is equal to -5, the test expression is false and body of else is executed and body of if
is skipped.
When num is equal to 0, the test expression is true and body of if is executed and body of
else is skipped.
Syntax
if test expression:
statement(s)
elif test expression:
statement(s)
else:
statement(s)
Core Python does not provide switch or case statements as in other languages, but we can
use if..elif...statements to simulate switch case as follows:
3.10 Problem Solving and Python Programming
Flowchart
If Test False
expression
True
Elif Test False
Body of if expression
True
True
Example 1
#num = 0
num = -3
#num = 4.5
if num > 0:
print(“Positive number”)
elif num == 0:
print(“Zero”)
else:
print(“Negative number”)
Output
Negative number
Syntax
if expression1:
statement(s)
else:
if expression2:
statement(s)
else:
statement(s)
Control Flow 3.11
Flowchart
Statement n
The outer conditional contains two branches. The second branch contains another if
statement, which has two branches of its own. Those two branches could contain conditional
statements as well.
Example
num = float(input(“Enter a number: “))
if num >= 0:
if num == 0:
print(“Zero”)
else:
print(“Positive number”)
else:
print(“Negative number”)
Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero
3.12 Problem Solving and Python Programming
3.5 ITERATION
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on. There may be a situation when you need to execute a block
of code several number of times.
Types
(i) while loop
(ii) for loop
(iii) nested loop
It tests the condition before executing the loop body so this technique is known as Entry
controlled loop.
Syntax
while expression:
statement(s)
The condition may be any expression, and true is any non-zero value. The loop iterates
while the condition is true. When the condition becomes false, program control passes to the line
immediately following the loop.
Flowchart
Enter while loop
Test False
expression
True
Example
count = 0
while (count < 9):
print( ‘The count is:’, count)
count = count + 1
print (“Good bye!”)
Output
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
Syntax
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in the
sequence is assigned to the iterating variable iterating_var. Next, the statements block is executed.
Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the
entire sequence is exhausted.
Flowchart
for each item in sequence
Test No
expression
Yes
Example
numbers=[6,5,3,8,4,2,5,4,11]
sum=0
for val in numbers:
sum=sum+val
print(“ The sum is”, sum)
Output
The sum is 48
(iii) Break
It terminates the current loop and resumes execution at the next statement, just like the
traditional break statement in C.
The break statement can be used in both while and for loops.
Syntax
break
Flowchart
Example:
for val in "string":
if val == "i":
break
print(val)
print("The end")
Control Flow 3.15
Output
s
t
r
The end
In this program, it iterates through the "string" sequence.and check if the letter is "i", upon
which we break from the loop. Hence, we see in our output that all the letters until "i" gets printed.
After that, the loop terminates.
Continue:
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
Syntax
continue
Flowchart
The working of continue statement in for and while loop is shown below.
3.16 Problem Solving and Python Programming
Example:
for val in "string":
if val == "i":
continue
print(val)
print("The end")
Output
s
t
r
n
g
The end
This program is same as the above example except the break statement has been replaced
with continue.
We continue with the loop, if the string is "i", not executing the rest of the block. Hence, we
see in our output that all the letters except "i" gets printed.
Pass Statement
In Python programming, pass is a null statement. The difference between a comment and
pass statement in Python is that, while the interpreter ignores a comment entirely, pass is not ignored
Syntax
pass
Example:
for letter in ‘Python’:
if letter == ‘h’:
pass
Control Flow 3.17
Output
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
Number data types store numeric values. They are immutable data types, means that
changing the value of a number data type results in a newly allocated object. Number objects are
created when you assign a value to them.
For example, the function abs returns a new number – namely, the absolute value of its
argument:
>>> abs(−42)
42
Some functions are not fruitful. For example, suppose franklin refers to a Turtle object, the
function call franklin.forward(100) does not return anything. Instead it causes franklin to move
forward. In addition, all of the functions defined in the previous handout are not fruitful.
import math
def square(x):
return x * x
def circle area (diameter ):
radius = diameter / 2.0
return math.pi * square(radius)
3.18 Problem Solving and Python Programming
How python evaluates a return statement? Python evaluates fruitful functions pretty much
the same way as non-fruitful ones
(1) Evaluates the expression to produce a data value.
(2) Passes that data value back to the caller.
(3) Leaves the function immediately and returns to the location where the function was
called.
Python returns immediately when it reaches a return statement. The print statement in the
function body below will never be executed
def square(x):
return x * x # pytho n leaves function here . ..
print ("I am NEVER printed!") # . . . and never gets to here .
The square function must use a return statement because it is called inside the circle area
function. In other words, the point of this function is to share the result (i.e., the squared number)
with another part of our program (i.e., the circle area function).
Parameters
A callable object is an object that can accept some arguments (also called parameters) and
possibly return an object (often a tuple containing multiple objects). A function is the simplest
callable object in Python, but there are others, such as classes or certain class instances.
•• formal parameter — the identifier used in a method to stand for the value that is passed
into the method by a caller.
◦◦ For example, amount is a formal parameter of processDeposit
•• actual parameter — the actual value that is passed into the method by a caller.
◦◦ For example, the 200 used when processDeposit is called is an actual parameter.
◦◦ actual parameters are often called arguments
Control Flow 3.19
Example:
x in:
def cube(x):
return x*x*x
Pass-by-value parameter passing-- the value of the actual parameter is copied to the formal
parameter. With pass-by-value, there is no way for the actual parameter to change value as the
function gets its own copy.
In Python, scalar values are sent by-value. Lists and other objects are sent by reference.
A variable which is defined inside a function is local to that function. It is accessible from
the point at which it is defined until the end of the function, and exists for as long as the function
is executing. The parameter names in the function definition behave like local variables, but they
contain the values that we pass into the function when we call it. When we use the assignment
operator(=)inside a function, its default behavior is to create a new local variable – unless a variable
with the same name is already defined in the local scope.
3.20 Problem Solving and Python Programming
#Now we call the function, passing the value 7 as the first and only parameter
my_function(7)
# a and b still
exist print(a)
print(b)
# c and d don’t exist anymore -- these statements will give us name errors!
print(c)
print(d)
“I love Paris in the summer!”. The question is, what will happen, if we change the value of
s inside of the function f()? Will it affect the global variable as well? We test this in the following
piece of code:
Example:
def f():
s = “I love India!”
Control Flow 3.21
print(s)
s = “I love Tamilnadu!”
f()
print(s)
Output
I love India!
I love Tamilnadu!
What if we combine the first example with the second one, i.e. first access s with a print()
function, hoping to get the global value, and then assigning a new value to it? Assigning a value to
it, would mean creating a local variable s. So, we would have s both as a global and a local variable
in the same scope, i.e. the body of the function. Python doesn’t allow this ambiguity. So, it will
throw an error, as we can see in the following example:
def f():
global s
print(s)
s = “God is great!”
print(s)
s = “I am looking for a course in Engineering!”
f()
print(s)
We have solved our problem. There is no ambiguity left. The output of this small script
looks like this:
God is great!
God is great!
Local variables of functions can’t be accessed from outside, when the function call has
finished:
def f():
s = “I am globally not known”
print(s)
f()
print(s)
The following example shows a wild combination of local and global variables and function
parameters:
def foo(x, y):
global a
a = 42
x,y = y,x
b = 33
b = 17
c = 100
print(a,b,x,y)
a,b,x,y = 1,15,3,4
foo(17,4)
print(a,b,x,y)
Output:
42 17 4 17
42 15 3 4
x=3
f()
This program is correct and returns the number 3 as the output.
3.8 COMPOSITION
As you should expect by now, you can call one function from within another. This ability is
called composition.
As an example, we’ll write a function that takes two points, the center of the circle and a
point on the perimeter, and computes the area of the circle.
Assume that the center point is stored in the variables xc and yc, and the perimeter point is
in xp and yp. The first step is to find the radius of the circle, which is the distance between the two
points. Fortunately, we’ve just written a function, distance, that does just that, so now all we have
to do is use it:
radius = distance (xc, yc, xp, yp)
The second step is to find the area of a circle with that radius and return it. Again we will
use one of our earlier functions:
result = area(radius)
return result
Wrapping that up in a function, we get:
def area2(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
3.24 Problem Solving and Python Programming
We called this function area 2 to distinguish it from the area function defined earlier.
The temporary variables radius and result are useful for development, debugging, and
single-stepping through the code to inspect what is happening, but once the program is working, we
can make it more concise by composing the function calls:
def area2(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))
Boolean functions
Functions can return booleans, which is often convenient for hiding complicated tests inside
functions.
Example:
def is_divisible(x, y):
if x % y == 0:
return True
else:
return False
It is common to give boolean functions names that sound like yes/ no questions; is_divisible
returns either True or False to indicate whether x is divisible by y.
Example:
>>> is_divisible(6, 4)
False
>>> is_divisible(6, 3)
True
The result of the == operator is a boolean, so we can write the function more concisely by
returning it directly:
def is_divisible(x, y):
return x % y == 0
Boolean functions are often used in conditional statements:
if is_divisible(x, y):
print ‘x is divisible by y’
It is common to give boolean functions names that sound like yes/ no questions; is_divisible
returns either True or False to indicate whether x is divisible by y.
3.9 RECURSION
A recursive definition is similar to a circular definition, in the sense that the definition
contains a reference to the thing being defined.
If you looked up the definition of the factorial function, denoted with the symbol !, you
might get something like this:
0! = 1
n! = n (n−1)!
This definition says that the factorial of 0 is 1, and the factorial of any other value, n, is n
multiplied by the factorial of n−1.
So 3! is 3 times 2!, which is 2 times 1!, which is 1 times 0!. Putting it all together, 3! equals
3 times 2 times 1 times 1, which is 6.
If you can write a recursive definition of something, you can usually write a Python program
to evaluate it. The first step is to decide what the parameters should be. In this case it should be clear
that factorial takes an integer:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
Otherwise, and this is the interesting part, we have to make a recursive call to find the
factorial of n−1 and then multiply it by n:
def factorial(n):
if n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
return result
3.26 Problem Solving and Python Programming
Explanation
If we call factorial with the value 3:
Since 3 is not 0, we take the second branch and calculate the factorial of n-1...
Since 2 is not 0, we take the second branch and calculate the factorial of n-1...
Since 1 is not 0, we take the second branch and calculate the factorial of n-1...
Since 0 is 0, we take the first branch and return 1 without making any more recursive
calls.
The return value (1) is multiplied by n, which is 1, and the result is returned.
The return value (1) is multiplied by n, which is 2, and the result is returned.
The return value (2) is multiplied by n, which is 3, and the result, 6, becomes the return
value of the function call that started the whole process.
Here is what the stack diagram looks like for this sequence of function calls:
Stack Diagram
The return values are shown being passed back up the stack. In each frame, the return value
is the value of result, which is the product of n and recurse.
In the last frame, the local variables recurse and result do not exist, because the branch that
creates them does not execute.
3.10 STRINGS
Strings are amongst the most popular types in Python. We can create them simply by
enclosing characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable.
For example −
var1 ='Hello World!'
var2 ="Python Programming"
Accessing Values in Strings
Python does not support a character type; these are treated as strings of length one, thus also
considered a substring.
Control Flow 3.27
To access substrings, use the square brackets for slicing along with the index or indices to
obtain your substring. For example −
var1 = 'Hello World!'
var2 = "Python Programming"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])
When the above code is executed, it produces the following result −
var1[0]: H
var2[1:5]: ytho
Updating Strings
You can "update" an existing string by (re)assigning a variable to another string. The new
value can be related to its previous value or to a completely different string altogether. For example
var1 = 'Hello World!'
print ("Updated String :- ", var1[:6] + 'Python')
When the above code is executed, it produces the following result −
Updated String :- Hello Python
Escape Characters
Following table is a list of escape or non-printable characters that can be represented with
backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
Backslash notation Hexadecimal character Description
\a 0x07 Bell or alert
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\nnn Octal notation, where n is in the range 0.7
\r 0x0d Carriage return
\s 0x20 Space
\t 0x09 Tab
\v 0x0b Vertical tab
\x Character x
3.28 Problem Solving and Python Programming
Example
print “My name is %s and weight is %d kg!” % (‘Zara’, 21)
Output
My name is Zara and weight is 21 kg!
Here is the list of complete set of symbols which can be used along with % −
Control Flow 3.29
Triple Quotes
Python’s triple quotes comes to the rescue by allowing strings to span multiple lines,
including verbatim NEWLINEs, TABs, and any other special characters.
The syntax for triple quotes consists of three consecutive single ordouble quotes.
para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print (para_str)
When the above code is executed, it produces the following result. Note how every single
special character has been converted to its printed form, right down to the last NEWLINE at the end
of the string between the "up." and closing triple quotes. Also note that NEWLINEs occur either
with an explicit carriage return at the end of a line or its escape code (\n) −
This is a long string that is made up of several lines and non-printable characters such as:
TAB ( ) and they will show up that way when displayed. NEWLINEs within the string,
whether explicitly given like this within the brackets [], or just a NEWLINE within the variable
assignment will also show up.
Raw strings do not treat the backslash as a special character at all. Every character you put
into a raw string stays the way you wrote it
3.30 Problem Solving and Python Programming
print ‘C:\\nowhere’
Output
C:\nowhere
Now let’s make use of raw string. We would put expression inr ’expression’ as follows −
print r’
C:\\nowhere’
Output
C:\\nowhere
The standard zero-based index numbers give easy access to chars near the start of the string.
As an alternative, Python uses negative numbers to give easy access to the chars at the end of the
string: s[-1] is the last char ‘o’, s[-2] is ‘l’ the next-to-last char, and so on. Negative index numbers
count back from the end of the string:
s[-1] is ‘o’ – last char (1st from the end)
s[-4] is ‘e’ – 4th from the end
s[:-3] is ‘He’ – going up to but not including the last 3 chars.
s[-3:] is ‘llo’ – starting with the 3rd char from the end and extending to the end of the
string.
It is a neat truism of slices that for any index n, s[:n] + s[n:] == s. This works even for n
negative or out of bounds. Or put another way s[:n] and s[n:] always partition the string into two
string parts, conserving all the characters. As we’ll see in the list section later, slices work with lists
too.
Strings are immutable, which means you cannot change an existing string. The best you can
do is create a new string that is a variation on the original.
reeting = “Hello, world!”
newGreeting = ‘J’ + greeting[1:]
print(newGreeting)
print(greeting)
Output
Jello, world!
Hello, world!
The solution here is to concatenate a new first letter onto a slice of greeting. This operation
has no effect on the original string.
Method Description
Python String isnumeric() Checks Numeric Characters
Python String isprintable() Checks Printable Character
Python String isspace() Checks Whitespace Characters
Python String istitle() Checks for Titlecased String
Python String isupper() returns if all characters are uppercase characters
Python String join() Returns a Concatenated String
Python String ljust() returns left-justified string of given width
Python String rjust() returns right-justified string of given width
Python String lower() returns lowercased string
Python String upper() returns uppercased string
Python String swapcase() swap uppercase characters to lowercase; vice versa
Python String lstrip() Removes Leading Characters
Python String rstrip() Removes Trailing Characters
Python String capitalize() Converts first character to Capital Letter
Python String center() Pads string with specified character
Python String casefold() converts to casefolded strings
Python String count() returns occurrences of substring in string
Python String endswith() Checks if String Ends with the Specified Suffix
Python String expandtabs() Replaces Tab character With Spaces
Python String encode() returns encoded string of given string
Python String find() Returns the Lowest Index of Substring
Python String format() formats string into nicer output
Python String index() Returns Index of Substring
Python String isalnum() Checks Alphanumeric Character
Python String isalpha() Checks if All Characters are Alphabets
Python String isdecimal() Checks Decimal Characters
Python String isdigit() Checks Digit Characters
Python String isidentifier() Checks for Valid Identifier
Python String islower() Checks if all Alphabets in a String are Lowercase
Python String isnumeric() Checks Numeric Characters
Python String isprintable() Checks Printable Character
Python String isspace() Checks Whitespace Characters
Python String istitle() Checks for Titlecased String
Python String isupper() returns if all characters are uppercase characters
Python String join() Returns a Concatenated String
Python String ljust() returns left-justified string of given width
Python String rjust() returns right-justified string of given width
Control Flow 3.33
Method Description
Python String lower() returns lowercased string
Python String upper() returns uppercased string
Python String swapcase() swap uppercase characters to lowercase; vice versa
Python String lstrip() Removes Leading Characters
Python String rstrip() Removes Trailing Characters
Python String capitalize() Converts first character to Capital Letter
Python String center() Pads string with specified character
Python String casefold() converts to casefolded strings
Python String count() returns occurrences of substring in string
Python String endswith() Checks if String Ends with the Specified Suffix
Python String expandtabs() Replaces Tab character With Spaces
Python String encode() returns encoded string of given string
Python String find() Returns the Lowest Index of Substring
Python String format() formats string into nicer output
Python String index() Returns Index of Substring
Python String isalnum() Checks Alphanumeric Character
Example :
import string
text = “Monty Python’s Flying Circus”
print “upper”, “=>”, string.upper(text)
print “lower”, “=>”, string.lower(text)
print “split”, “=>”, string.split(text)
print “join”, “=>”, string.join(string.split(text), “+”)
print “replace”, “=>”, string.replace(text, “Python”, “Java”)
print “find”, “=>”, string.find(text, “Python”), string.find(text, “Java”)
print “count”, “=>”, string.count(text, “n”)
Output
upper => MONTY PYTHON’S FLYING CIRCUS lower => montypython’s flying
circus
split => [‘Monty’, “Python’s”, ‘Flying’, ‘Circus’] join => Monty+Python’s+Flying+Circus
replace => Monty Java’s FlyingCircus
find => 6 -1
count => 3
3.34 Problem Solving and Python Programming
List basics
A list in Python is just an ordered collection of items which can be of any type. By comparison
an array is an ordered collection of items of a single type - so in principle a list is more flexible
than an array but it is this flexibility that makes things slightly harder when you want to work with
a regular structure.
A list is also a dynamic mutable type and this means you can add and delete elements from
the list at any time.
To define a list you simply write a comma separated list of items in square brackets:
myList=[1,2,3,4,5,6]
This looks like an array because you can use “slicing” notation to pick out an individual
element - indexes start from 0.
Example:
print myList[2]
will display the third element, i.e. the value 3 in this case. Similarly to change the third
element you can assign directly to it:
myList[2]=100
The slicing notation looks like array indexing but it is a lot more flexible.
Example:
myList[2:5]
is a sublist from the third element to the fifth i.e. from myList[2] to myList[4].
Notice that the final element specified i.e. [5] is not included in the slice.
Also notice that you can leave out either of the start and end indexes and they will be
assumed to have their maximum possible value.
Example:
myList[5:]
is the list from List[5] to the end of the list and
myList[:5]
is the list up to and not including myList[5] and
Control Flow 3.35
myList[:]
is the entire list.
List slicing is more or less the same as string slicing except that you can modify a slice.
Example:
myList[0:2]=[0,1]
has the same effect as
myList[0]=0
myList[1]=1
Finally is it worth knowing that the list you assign to a slice doesn’t have to be the same size
as the slice - it simply replaces it even if it is a different size.
ILLUSTRATIVE PROGRAMS :
Square Root :
import math
a=float(input("Enter a value"))
print("The exponential value of {0} is ".format(a),math.exp(a))
Output:
Enter 'x' for exit.
Enter a number: 3
Square Root of 3.000 is 1.732
Enter 'x' for exit.
Enter a number: 16
Square Root of 16.000 is 4.000
Enter 'x' for exit.
Enter a number: x
return y
for k in range(int(y / 2), 0, -1):
if x % k == 0 and y % k == 0:
gcd = k
break
print("The Greatest Common Divisor of {0} and {1} is".format(x,y),gcd)
#gcd(a,b)
Output
x value=90
y value=100
The Greatest Common Divisor of 90 and 100 is 10
BinarySearch:
def binarySearch(myItem,myList):
found = False
bottom = 0
top = len(myList) - 1
while bottom <= top and not found:
middle = (bottom+top)//2
if myList[middle] == myItem:
found = True
elif myList[middle] < myItem:
bottom = middle + 1
else:
top = middle-1
return found
if __name__=="__main__":
#numberList=[1,3,4,8,69,45,32,46,78,20,25,46,10,75,36,99,100]
numberList = []
while True:
print("Enter '-1' for exit.")
list1=int(input("Enter numbers: "))
Control Flow 3.37
if list1 == -1:
break
else:
numberList.append(list1)
print("The created number list is \n",numberList)
number = int(input("Enter your number to search: "))
isitFound = binarySearch(number,numberList)
if isitFound:
print("The entered number {0} is in the list".format(number))
else:
print("The entered number {0} is not in the list".format(number))
Output
Enter your number to search: 45
The entered number 45 is in the list
Enter your number to search: 1000
The entered number 1000 is not in the list
Linear Search :
def linearSearch(myItem,myList):
found = False
position = 0
while position < len(myList) and not found:
if myList[position] == myItem:
found = True
position = position +1
return found
if __name__=="__main__":
shopping = []
while True:
print("Enter 'x' for exit.")
list1=input("Enter items: ")
3.38 Problem Solving and Python Programming
if list1 == 'x':
break
else:
shopping.append(list1)
print("The created list is \n",shopping)
#shopping=["Apple","Banana","Orange","Guvava","Pienapple","Bread","Milk"]
item = input("Enter your item to search: ")
isitFound = linearSearch(item,shopping)
if isitFound:
print("Your item is in the list")
else:
print("Sorry your item not in the list")
Output
Enter your item to search: Apple
Your item is in the list
Enter your item to search: Butter
Sorry your item not in the list
UNIT – 4
COMPOUND DATA:
LISTS, TUPLES, DICTIONARIES
4.1 LISTS
A list is a sequence of any type of values and can be created as a set of comma-separated
values within square brackets. The values in a list are called elements or items. A list within another
list is called nested list.
Sample Output:
[‘Ram’, ‘Chennai’, 2017]
[10, 20, 30, 40, 50] [ ]
[‘Priya’, 2017, 99.8, [‘Mumbai’, ‘India’]]
For eg, in a list stulist = [‘Ram’, ‘Chennai’, 2017], stulist[1] returns Chennai as its output.
The following code is another example for concatenation, where a list contains elements of
different data types:
Code Output
stulist = [‘Ram’, ‘Chennai’, 2017] [‘Ram’, ‘Chennai’, 2017]
newlist = stulist+[‘CSE’] [‘Ram’, ‘Chennai’, 2017, ‘CSE’]
print stulist
print newlist
If the first index is omitted, the slice starts at the beginning of the string. If the second index
is omitted, the slice goes to the end of the string. If the first index is greater than or equals to the
second, the slice is an empty string. If both indices are omitted, the slice is a given string itself.
Compound Data: Lists, Tuples, Dictionaries 4.3
1. append
Adds element to the end of specified list and does not return any value.
Syntax: listname.append(element)
Sample output:
After appending
[‘Ram’, ‘Chennai’, 2017, ‘CSE’]
2. count
Returns the number of occurrences of an element in a specified list.
Syntax: listname.count(element)
print stulist
print ‘Count for Chennai : ‘, stulist.count(‘Chennai’)
print ‘Count for 2017 : ‘, stulist.count(2017)
Sample output:
[‘Ram’, ‘Chennai’, 2017, ‘Priya’, ‘Mumbai’, 2017]
Count for Chennai : 1
Count for 2017 : 2
3. extend
Appends the contents of secondlist to the firstlist and does not return any value.
Syntax: firstlist.extend(secondlist)
Sample output:
Before Extend : [‘Ram’, ‘Chennai’, 2017]
After Extend : [‘Ram’, ‘Chennai’, 2017, ‘CSE’]
4. index
Returns the index of an element, if an element is found in the specified list. Else, an exception
is raised.
Syntax: listname.index(element)
6. insert
Inserts the given element at the given index in a specified list and does not return any value
Syntax: listname.insert(index, element)
Sample output:
Before insert : [‘Ram’, ‘Chennai’, 2017]
After insert : [‘Ram’, ‘CSE’, ‘Chennai’, 2017]
7. pop
Removes and returns the element from the end of specified list
Syntax: listname.pop()
Sample output:
Initial list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
Popping the last item : 92.7
After popping the last item, the list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’]
8. pop(index)
Removes and returns the element at given index.
Syntax: listname.pop(index)
9. remove
Removes an element from the list and does not return any value.
Syntax: listname.remove(element)
10. reverse
Reverses the entire list.
Syntax: listname.reverse()
Sample output:
Initial list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
After reversing, the list is : [92.7, ‘CSE’, 2017, ‘Chennai’, ‘Ram’]
Compound Data: Lists, Tuples, Dictionaries 4.7
11. sort
Sorts the list in ascending order.
Syntax: listname.sort()
Sample output:
Before sorting : [6, 28, 11, 4, 20, 26, 13, 12]
After sorting is : [4, 6, 11, 12, 13, 20, 26, 28]
Sample output:
Initial list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
After sorting, the list is : [92.7, 2017, ‘CSE’, ‘Chennai’, ‘Ram’]
for i in range(len(numlist)):
print i
Output:
0
1
2
3
4
Here, len is a function that returns the number of elements in the list and range is a function
that returns a list of indices from 0 to n − 1, where n is the length of the list. The following code
gives an idea to traverse the list and to update the elements of a list with the help of range and len
functions in for loop:
numlist = [1, 2, 3, 4, 5]
for i in range(len(numlist)):
numlist[i]=numlist[i]+10
for i in numlist:
print i
Output:
11
12
13
14
15
A for loop over an empty list never executes the body and is shown in the following code:
numlist = []
for i in numlist:
print ‘never executes’
4.1.6 Mutability
The list is a mutable data structure. This means that its elements can be replaced, inserted
and removed. A slice operator on the left side of an assignment operation can update single or
multiple elements of a list. New elements can be added to the list using append() method.
The following code replaces ‘Ram’ which is at index 0 in the stulist by ‘Priya’. The values
are shown in the output for both instances.
stulist = [‘Ram’, ‘Chennai’, 2017]
Compound Data: Lists, Tuples, Dictionaries 4.9
Output:
Before mutation [‘Ram’, ‘Chennai’, 2017]
After mutation [‘Priya’, ‘Chennai’, 2017]
4.1.7 Aliasing
When we create two lists, we get two objects as shown in the following code and the
corresponding state diagram (Figure 4.1):
list1=[1,2]
list2=[1,2]
print list1 is list2 # prints False, as list1 and list2 are not the same object
List 1 [1,2]
List 2 [1,2]
In the following code, there are two references to the same object. An object with more than
one reference has more than one name, so we say that the object is aliased.
list1=[1,2]
list2=list1
print list1 is list2 # prints True, as list1 and list2 are the same object
The state diagram for the above code is as shown in Figure 4.2:
List 1
[1,2]
List 2
Sample Code
list1=[1,2]
list2=list1
print ‘List1 is :’, list1
print ‘List2 is :’, list2
list1[0]=10
print ‘List1 is :’, list1
print ‘List2 is :’, list2
list2[1]=20
print ‘List1 is :’, list1
print ‘List2 is :’, list2
Sample Output:
List1 is : [1, 2]
List2 is : [1, 2]
List1 is : [10, 2]
List2 is : [10, 2]
List1 is : [10, 20]
List2 is : [10, 20]
Though aliasing can be helpful, it may lead to errors. So, avoid aliasing in mutable objects.
To prevent aliasing in lists, a new empty list can be created and the contents of the existing list can
be copied to it, as given in the following code:
Output:
List1 is : [1, 2]
List2 is : [1, 2]
After modification
List1 is : [10, 2]
List2 is : [1, 2]
In lists, cloning operation can be used to create a copy of an existing list so that changes
made in one copy of list will not affect another. The copy contains the same elements as the original.
Method 1: list() function:
Built-in list() function can be used for cloning lists with the following syntax:
Newlistname = list(Oldlistname)
Sample Code:
oldlist = [10, 20, 30, 40, 50]
newlist = list(oldlist)
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
oldlist[0]=5
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
Sample Output:
Old list is : [10, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]
Old list is : [5, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]
Method 2: copy.copy() function:
Syntax:
Newlistname = copy.copy(Oldlistname)
copy.copy() is little slower than list() since it has to determine data type of old
list first.
4.12 Problem Solving and Python Programming
Sample Code:
import copy
oldlist = [10, 20, 30, 40, 50]
newlist = copy.copy(oldlist) # Returns a shallow copy of oldlist
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
oldlist[0]=5
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
Sample Output:
Old list is : [10, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]
Old list is : [5, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]
Method 3: copy.deepcopy() function:
Syntax
Newlistname = copy.deepcopy(Oldlistname)
Sample Code:
import copy
oldlist = [10, 20, 30, 40, 50]
newlist = copy.deepcopy(oldlist) # Returns a deep copy of oldlist
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
oldlist[0]=5
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
Sample Output:
Old list is : [10, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]
Old list is : [5, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]
Compound Data: Lists, Tuples, Dictionaries 4.13
copy() (also known as shallow copy) and deepcopy() differs in the usage of compound objects
that are objects containing other objects, like lists). copy() creates a new compound object first and
then inserts references to the objects of the original. deepcopy() constructs a new compound object
and then, recursively, inserts copies to the objects of the original. The following code illustrates the
use of deepcopy() for a compound (nested) list.
Sample Code:
import copy
oldlist = [1, 2, [‘a’,’b’]]
newlist = copy.deepcopy(oldlist)
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
newlist[0] = ‘c’
newlist[2][1] = ‘d’
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
Sample Output:
Old list is : [1, 2, [‘a’, ‘b’]]
New list is : [1, 2, [‘a’, ‘b’]]
Old list is : [1, 2, [‘a’, ‘b’]]
New list is : [‘c’, 2, [‘a’, ‘d’]]
The following program employs a function my_display() that creates and returns a new list.
Within my_display(), numlist is referenced as n.
Sample Code:
def my_display(n): # function definition
return n[:]
numlist = [10, 20, 30, 40, 50]
print ‘numlist is : ‘, numlist
newlist=my_display(numlist) # function call
print ‘newlist is : ‘, newlist
Sample Output:
numlist is : [10, 20, 30, 40, 50]
newlist is : [10, 20, 30, 40, 50]
The following program includes a function my_display() that creates and displays the
elements of a list.
Sample Code:
def my_display(n): # function definition
nlist= n[:]
print ‘Within a function : ‘, nlist
numlist = [10, 20, 30, 40, 50]
print ‘numlist is : ‘, numlist
my_display(numlist) # function call
Sample Output:
numlist is : [10, 20, 30, 40, 50]
Within a function : [10, 20, 30, 40, 50]
Output:
Initial list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
Now the list is : [‘Ram’, 2017, ‘CSE’, 92.7]
pop() and remove() methods can also be used to delete list elements.
Code Output
list1 = [10, ‘xyz’]
list2 = [20, ‘abc’]
list3 = [10, ‘xyz’]
print ‘Comparing list1 and list2 ‘, cmp(list1, list2) Comparing list1 and list2 -1
print ‘Comparing list2 and list3 ‘, cmp(list2, list3) Comparing list2 and list3 1
print ‘Comparing list1 and list3 ‘,cmp(list1, list3) Comparing list1 and list3 0
1. len
Returns the total number of elements in a list.
Syntax: len(listname)
Code Output
stulist = [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
print ‘Length is : ‘, len(stulist) Length is : 5
2. max
Returns the largest item from the list.
Syntax: max(listname)
3. min
Returns the smallest item from the list.
Syntax: min(listname)
Code Output
numlist = [6, 28, 11, 4, 20, 26, 13, 12]
print ‘Maximum is : ‘, max(numlist) Maximum is : 28
print ‘Minimum is : ‘, min(numlist) Minimum is : 4
4.16 Problem Solving and Python Programming
4. list
Converts a tuple into a list and returns a list.
Syntax: listname=list(tuplename)
Code Output
stu_tuple = (‘Anu’, ‘Chennai’, 2017, ‘CSE’, 92.7) Tuple elements : (‘Anu’, ‘Chennai’,
print ‘Tuple elements : ‘, stu_tuple 2017, ‘CSE’, 92.7)
stulist = list(stu_tuple) List elements : [‘Anu’, ‘Chennai’,
print ‘List elements : ‘, stulist 2017, ‘CSE’, 92.7]
Syntax:
[expression for item in list if conditional]
This is equivalent to:
for item in list:
if conditional:
expression
new_list = [expression(i) for i in old_list if filter(i)]
new_list is the resultant list. expression(i) is based on the variable used for each element in
the old list. If needed filter can be applied using if statement.
Example:
from types import *
a_list = [1, ‘4’, 9, ‘a’, 0, 4]
Compound Data: Lists, Tuples, Dictionaries 4.17
Sample output:
[ 1, 81, 0, 16 ]
Output Input
Expression Sequence
•• The iterator part iterates through each member e of the input sequence a_list.
•• The predicate checks if the member is an integer.
•• If the member is an integer then it is passed to the output expression, squared, to become
a member of the output list.
Example:
x=[I for I in range(10)]
print x
Sample Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
squares=[x**2 for x in range(10)]
print squares
Sample Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Sample Output:
[‘t’, ‘i’, ‘a’, ‘e’]
Sample Output:
[11, 12, 13, 21, 22, 23, 31, 32, 33]
This example, adds the values in list x to each value in list y.
4.2 TUPLES
A tuple is a collection of values of different types. Unlike lists, tuple values are indexed by
integers. The important difference is that tuples are immutable.
•• Tuples generally used for heterogeneous (different) datatypes and list for homogeneous
(similar) datatypes.
•• Tuples are immutable, so iterating through tuple is faster than the list. There is a slight
performance enhancement through list.
•• Tuple elements can be used as key for a dictionary. With list, this is not possible.
•• If you have data that doesn’t change, implementing it as tuple will guarantee that it
remains write-protected.
As we have seen before, a tuple is a comma-separated values.
Syntactically, a tuple can be represented like this:
>>> t = ‘a’, ‘b’, ‘c’, ‘d’, ‘e’
Even if it is not necessary to parentheses to enclose tuples, it is so.
t1 = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
t2=(1,2,3,4,5)
The empty tuple can be created by simply using the parentheses.
t3=()
The tuple with one element can be created as follows. It takes one comma after the element.
t4=(‘s’,)
print type(t4)
Output:
<type ‘tuple’>
t5 = ‘a’,
print type(t5)
Compound Data: Lists, Tuples, Dictionaries 4.19
Output:
<type ‘tuple’>
A value of tuple in parentheses is not a tuple. The following program code explain this.
t2 = (‘a’)
print type(t2[1])
Output:
<type ‘str’>
The built –in function tuple can be used to create tuple. To create an empty tuple no arguments
is passed in the built-in function.
t = tuple() #tuple is the built-in function
print t
Output:
()
If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of
the sequence:
t = tuple(‘hello’)
print t
Output:
(‘h’, ‘e’, ‘l’, ‘l’, ‘o’)
t = tuple(’12345’)
print t
Output:
(‘1’, ‘2’, ‘3’, ‘4’, ‘5’)
# parentheses is optional
tup3 = “hai”,
print type(tup3)
Output:
<class ‘str’>
<class ‘tuple’>
<class ‘tuple’>
Output:
tup1[0]: C
tup1[1]: C++
tup2[1:5]: [2, 3, 4, 5, 6, 7]
a
#t1[2.0]
# nested tuple
nest_tup = (“hello”, [8, 4, 6], (1, 2, 3))
# nested index
print nest_tup[0][4]
# nested index
# Output: 4
print nest_tup[1][2]
print nest_tup[2][0]
Output:
p
n
t
n
p
o
6
1
Output:
(‘A’, ‘b’, ‘c’, ‘d’, ‘e’)
4.22 Problem Solving and Python Programming
Here, the first element ‘a’ is replaced with ‘A’. A new tuple is created with the value ‘A’ is
combined with tuple t3 having index from 1 to the last element. The tuple value t3[0]=’a’ is replaced
by ‘A’.
Output:
(‘C’, ‘C++’, ‘python’, 1997, 2000)
After deleting :
print t1
Output:
1
2
In general to swap the values of two variables, a temporary variable is used. For example
to swap x and y:
temp = x
x=y
y = temp
This solution is clumsy; the tuple assignment is more elegant.
a, b = b, a
In the expression, the left side is a tuple of variables; the right side is a tuple of expressions.
4.24 Problem Solving and Python Programming
Each value is assigned to its respective variable. All the expressions on the right side are evaluated
before any of the assignments.
The number of variables on the left side and the number of values on the right must be the
same:
a, b = 1, 2
In this a is assigned with 1 and b is assigned with 2.
For the assignment,
a, b= 1,2,3
This statement creates error, as
ValueError: too many values to unpack
The right side of the assignment statement can be any kind of sequence (string, list or tuple).
For example, to split an email address into a user name and a domain, the split function can be used
as follows.
mail_id = ‘[email protected]’
uname, domain = mail_id.split(‘@’)
print uname
print domain
Output:
students
python.org
In this, the split function is used to separate the value into two parts. The return value from
the split function is a list with two elements; the first element is assigned to uname, the second is
assigned to domain.
Output:
()
(1, 2, 3)
(1, ‘Hello’, 2.4)
(‘World’, [8, 4, 6], (1, 2, 3))
(3, 4.6, ‘ABC’)
3
4.6
ABC
Output:
2
1
3
Output:
True
False
False
True
Progrmming-languages C
Progrmming-languages C++
Output:
(2, 1)
Here, the built-in function divmod is used which takes two arguments and returns a tuple of
two values, the quotient and remainder. The result can be stored as a tuple as in previous program
code. Or tuple assignment can be used to store the elements separately as in the following code.
Output:
2
1
One more example to explain tuples as return values. The built-in functions min and max
are used to find the smallest and largest elements of a sequence. The function min_max computes
both and returns a tuple of two values.
Example:
def printall (*args): # the function takes several args
print args
The argument name may be anything, but args is conventional. Here is the example to show
how the function printall works:
printall(1, 2.0, ‘3’)
(1, 2.0, ‘3’)
The complement of gather is scatter. To pass a sequence of values to a function as multiple
arguments, the * operator can be used. For example, consider the divmod function which takes
exactly two arguments; doesn’t work with a tuple of variable length arguments:
t = (7, 3)
divmod(t)
Output:
TypeError: divmod expected 2 arguments, got 1
But if you scatter the tuple, it works:
Instead of the above code, the code given below can be used for variable length arguments.
divmod(*t)
(2, 1)
There are some other built-in functions which use variable-length argument tuples.
The max and min functions take any number of arguments:
max(1,2,3)
Output:
3
The sum function does not take variable length arguments. It gives error.
sum(1,2,3)
Output:
TypeError: sum expected at most 2 arguments, got 3
True
The sort function also works in the same way. It sorts primarily by first element. But if there
is a tie, it sorts by second element, and so on. This feature lends itself to a pattern called DSU. DSU
stands for Decorate, Sort, Undecorate.
DSU:
Decorate a sequence by building a list of tuples with one or more sort keys preceding the
elements from the sequence,
Sort the list of tuples, and Undecorate by extracting the sorted elements of the sequence.
Output:
-1
1
-1
1
0
0
-1
1
4.3 DICTIONARIES
Dictionary is an unordered collection of items. It is similar to a list, but in list elements can
be accessed using index which must be an integer. In Dictionary we access values by looking up a
key instead of an index. A key can be any string or number. For example, dictionaries can be used
for things like phone books (pairing a name with a phone number), login pages (pairing an e-mail
address with a username).
Each item in dictionary has a key: value pair and the list of items are enclosed inside curly
braces {} separated by comma. The values can be of any data type and can repeat; keys must be of
immutable types (string, number or tuple with immutable elements) and must be unique.
Dictionaries in Python are implemented using hash table. It is an array whose indexes are
obtained using a hash function on the keys. A hash function takes a key value and returns hash
value, an integer. This hash value is used in the dictionary to store and lookup key-value pairs. So
keys in dictionary must be hashable.
# empty dictionary
my_dict = {}
print my_dict
Sample Output:
{}
The following dictionary uses integer as keys and string as values.
# dictionary with integer keys
Compound Data: Lists, Tuples, Dictionaries 4.31
Sample Output:
{1: ‘apple’, 2: ‘ball’}
ball
The following dictionary uses mixed keys. For item 1, both key and its corresponding value
are string. In item 2, the key is an integer and the value is a list.
Sample Output:
{1: [2, 4, 3], ‘name’: ‘John’}
John
[2, 4, 3]
In the output, the order of the key-value pairs is not the same. In general, the order of items
in dictionary is unpredictable. In the following example, using list, a mutable data type as key
results in error message.
dic = { [1,2,3]:”abc”}
Traceback (most recent call last):
File “main.py”, line 1, in <module>
dic = { [1,2,3]:”abc”}
TypeError: unhashable type: ‘list’
Tuple, an immutable data type can be used as key, which is shown in following example.
my_dic = { (1,2,3):”abc”, 3.14:”abc”}
print my_dic
Sample Output:
{3.14: ‘abc’, (1, 2, 3): ‘abc’}
An exception will be raised when we try to access a key that does not exist in dictionary. In
the following example, accessing my_dict[2] results in an error, as the key 2 not exist in dictionary.
4.32 Problem Solving and Python Programming
Sample Output:
Traceback (most recent call last):
File “main.py”, line 2, in <module>
print my_dict[2]
KeyError: 2
Sample Output:
{1: ‘apple’, 2: ‘ball’}
Function/Method Description
len(dict) Returns the length of dictionary which is equal to
number of pairs in the dictionary.
cmp(dict1,dict2) Compare items of two dictionaries
sorted(dict) Returns sorted list of keys in dictionary
dict.clear() Remove all items from dictionary
dict.copy() Returns a shallow copy of dictionary
dict.fromkeys(seq[, v]) Return a new dictionary with keys from seq and value
equal to v
dict.get(key) Returns the value of key. If key does not exists, it returns
None
dict.pop(key) Remove the item with key and returns its value.
KeyError occurs when key is not found
dict.popitem() Remove and return an arbitary item (key, value). Raises
KeyError if the dictionary is empty.
dict.items() Returns a list of dict’s (key, value) tuple pairs
dict.keys() Returns list of dictionary dict’s keys
dict1.update(dict2) Update the dictionary dict1 with the key/value pairs
from dict2, overwriting existing keys.
Compound Data: Lists, Tuples, Dictionaries 4.33
Sample Output:
9
{1: 1, 2: 4, 4: 16, 5: 25}
(1, 1)
{2: 4, 4: 16, 5: 25}
{2: 4, 4: 16}
{}
4.34 Problem Solving and Python Programming
We can also use the del keyword to remove individual items or the entire dictionary itself.
If we try to access the deleted dictionary, it will raise an Error.
del squares # delete the dictionary itself
print squares #throws error
Traceback (most recent call last):
File “main.
py”, line 11, in <module>
print squares NameError: name ‘squares’ is not defined
Sample Output:
{‘Maths’: 0, ‘Science’: 0, ‘English’: 0}
(‘Maths’, 0)
(‘Science’, 0)
(‘English’, 0)
[‘English’, ‘Maths’, ‘Science’]
value=dict[key]
Whereas, reverse lookup is the process of finding the key for a given value. There is no
direct method to handle reverse lookup. The following function takes a value and returns the first
key that map to that value.
def get_Value(dic,value):
for name in dic:
if dic[name] == value:
return name
raise ValueError
squares={1:1,2:4,3:9,4:16,5:25}
print get_Value(squares,4) # successful reverse lookup
Sample Output:
2
In this example, raise keyword is used to raise/activate an exception. ValueError indicates
that there is something wrong with value of parameter. On unsuccessful reverse lookup, when the
value is not in the dictionary, the exception ValueError is raised. Unsuccessful reverse lookup result
in following error.
print get_Value(squares,6) # unsuccessful reverse lookup
Traceback (most recent call last):
File “main.py”, line 7, in <module>
print get_Value(squares,6)
File “main.py”, line 5, in get_Value
raise ValueError
ValueError
def invert_dict_nonunique(d):
newdict = {}
for k, v in d.iteritems():
newdict.setdefault(v, []).append(k)
return newdict
d = {‘child1’: ‘parent1’,
‘child2’: ‘parent1’,
‘child3’: ‘parent2’,
‘child4’: ‘parent2’,
}
print invert_dict_nonunique(d)
Sample Output:
{‘parent2’: [‘child3’, ‘child4’], ‘parent1’: [‘child1’, ‘child2’]}
In this example the loop iterates through dictionary items where k represents key and v
represents value. The setdefault() method will set newdict[v]=[] and append the key value to list..
For example, consider the recursive version to calculate the Fibonacci numbers. The
following code to compute Fibonacci series has an exponential runtime behavior.
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
Compound Data: Lists, Tuples, Dictionaries 4.37
The runtime behavior of this recursive version can be improved by adding a dictionary to
memorize previously calculated values of the function.
def memoize(f):
memo = {}
def helper(x):
if x not in memo:
memo[x] = f(x)
return memo[x]
return helper
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
fib = memoize(fib)
print(fib(6)) # output the 6th number in Fibonacci series (series starts from 0th
position)
Sample Output:
8
memoize() takes a function as an argument. The function memorize() uses a dictionary
“memo” to store the function results. Though the variable “memo” as well as the function “f” are
local to memoize, they are captured by a closure through the helper function which is returned as a
reference by memoize(). So, the call memoize(fib) returns a reference to the helper() which is doing
what fib() would do on its own plus a wrapper which saves the calculated results. For an integer ‘n’
fib(n) will only be called, if n is not in the memo dictionary. If it is in it, we can output memo[n] as
the result of fib(n).
4.38 Problem Solving and Python Programming
memoize
Memo = {}
def helper (x):
if x not in memo:
memo[x]=f(x) Executing;
return memo[x] fib = memoize(fib)
return helper helper is returned
fib
if x not in memo:
if n==0: memo [x]= f(x)
return 0 return memo [x]
elseif n==1:
return 1
else:
return fib(n-1) + fib(n-2)
After having executed fib = memoize(fib) fib points to the body of the helper function,
which had been returned by memoize. The decorated Fibonacci function is called in the return
statement return fib(n-1) + fib(n-2), this means the code of the helper function which had been
returned by memorize.
Selection sort algorithm starts by comparing first two elements of an array and swapping if
necessary, i.e., if you want to sort the elements of array in ascending order and if the first element
is greater than second then, you need to swap the elements but, if the first element is smaller than
second, leave the elements as it is. Then, again first element and third element are compared and
swapped if necessary. This process goes on until first and last element of an array is compared.
This completes the first step of selection sort. The working of selection sort algorithm is shown in
Figure.4.3.
Compound Data: Lists, Tuples, Dictionaries 4.39
20 12 10 15 2 2 20 12 15 10 2 10 20 15 12 2 10 12 20 15
12 20 10 15 2 2 12 20 15 10 2 10 15 20 12 2 10 12 15 20
10 20 12 15 2 2 12 20 15 10 2 10 12 20 15
10 20 12 15 2 2 10 20 15 12
2 20 12 15 10
This algorithm is not suitable for large data sets as its average and worst case complexities
are of Ο(n2), where n is the number of items.
arr=[]
n=input(‘Enter number of elements’)
for i in range(0,n):
x=int(input(‘Enter number’))
arr.insert(i,x)
i+=1
for i in range(len(arr)):
for j in range(i, len(arr)):
if(arr[i] > arr[j]):
arr[i], arr[j] = arr[j], arr[i]
print ‘Sorted List:’, arr
Sample input/output:
Enter no5
enter no.12
enter no. 2
enter no.23
enter no. 4
enter no.5
Sorted List:
[2, 4, 5, 12, 23]
4.40 Problem Solving and Python Programming
4.4.2 Python program to sort a list of elements using the insertion sort algorithm
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item
at a time. Here, a sub-list is maintained which is always sorted. The array is searched sequentially and
unsorted items are moved and inserted into the sorted sub-list (in the same array). This algorithm is
suitable for small data sets. But it is much less efficient on large lists than more advanced algorithms
such as quicksort, heapsort, or merge sort. The worst case complexity of the algorithm is of Ο(n2),
where n is the number of items. Insertion sort is explained in figure 4.4.
def insertionsort(list):
for i in range(1,len(list)):
temp=list[i]
j=i-1
while temp<+list[j] and j>=0:
list[j+1]=list[j]
j=j-1
list[j+1]=temp
return list
arr=[]
n=input(‘Enter number of elements’)
for i in range(0,n):
x=int(input(‘Enter number’))
arr.insert(i,x)
i+=1
print insertionsort(arr)
Compound Data: Lists, Tuples, Dictionaries 4.41
Sample input/output:
Enter number of elements5
Enter number12
Enter number23
Enter number4
Enter number16
Enter number34
[4, 12, 16, 23, 34]
4.4.3 Python program to sort a list of elements using the merge sort algorithm
Merge sort is a sorting technique based on divide and conquer technique. It first divides the
array into equal halves and then combines them in a sorted manner. The basic steps involved in
merge sort algorithm are as follows: Given an array A.
1. Divide
If q is the half-way point between p and r, then we can split the subarray A[p..r] into two
arrays A[p..q] and A[q+1, r].
2. Conquer
In the conquer step, we try to sort both the subarrays A[p..q] and A[q+1, r]. If we haven’t yet
reached the base case, we again divide both these subarrays and try to sort them.
3. Combine
When the conquer step reaches the base step and we get two sorted subarrays A[p..q] and
A[q+1, r] for array A[p..r], we combine the results by creating a sorted array A[p..r] from
two sorted subarrays A[p..q] and A[q+1, r].
38 27 43 3 9 82 10
38 27 43 3 9 82 10
38 27 43 3 9 82 10
38 27 43 3 9 82 10
27 38 3 43 9 82 10
3 27 38 43 9 10 82
3 9 10 27 38 43 82
As shown in Figure. 4.5, the merge sort algorithm recursively divides the array into halves
until we reach the base case of array with 1 element. After that, the merge function picks up the
sorted sub-arrays and merges them to gradually sort the entire array. The worst case complexity of
the algorithm is O(n log n), where n is the number of items.
def merge_sort(sequence):
if len(sequence) < 2:
return sequence
m = len(sequence) / 2
return merge(merge_sort(sequence[:m]), merge_sort(sequence[m:]))
def merge(left, right):
result = []
i=j=0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
print merge_sort([5, 2, 6, 8, 5, 8, 1])
Sample output:
[1, 2, 5, 5, 6, 8, 8]
4.4.4 Python program to sort a list of elements using the Quick sort algorithm
Like Merge Sort, Quick Sort is a Divide and Conquer algorithm. It picks an element as
pivot and partitions the given array around the picked pivot. The pivot element can be selected using
following different ways.
(1) Always pick first element as pivot.
(2) Always pick last element as pivot.
(3) Pick a random element as pivot.
(4) Pick median as pivot.
The runtime of the algorithm varies based on the pivot selected. The basic idea behind this
algorithm is as follows.
1. Pick one element in the array, which will be the pivot.
2. Make one pass through the array, called a partition step, re-arranging the entries so that:
Compound Data: Lists, Tuples, Dictionaries 4.43
leftmark rightmark
leftmark rightmark
54 26 20 17 77 31 44 55 93 exchange 20 and 93
leftmark rightmark
leftmark rightmark
77 > 54 stop
54 26 20 17 44 31 77 55 93 31 < 54 stop
rightmark < leftmark
split point found
rightmark leftmark exchange 54 and 31
Sample Output:
[17, 20, 26, 31, 44, 54, 55, 77, 93]
Compound Data: Lists, Tuples, Dictionaries 4.45
4.4.5 Write a Python program to create a histogram from a given list of integers.
def histogram( items ):
for n in items:
output = ''
times = n
while( times > 0 ):
output += '*'
times = times - 1
print(output)
histogram([2, 3, 6, 5])
Sample Output:
**
***
******
*****
UNIT - 5
5.1 FILES
5.1.1 Reading and Writing
So far in the previous chapters, we have seen to work standard input and output through
input functions such as input () and raw_input() and output function print statement.
The raw_input Function:
The raw_input([prompt]) function reads one line from standard input and returns it as a
string (leaving the trailing newline).
Output:
Enter your input: Hello Python
Received input is : Hello Python
The input Function
The input([prompt]) function is similar to raw_input, except that it assumes the input as a
valid Python expression and returns the evaluated result.
Output:
Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40]
Now, we will see how to use actual data files. A text file is a sequence of characters stored on
a permanent storage medium such as hard drive, flash memory, or CD-ROM. Python offers some
basic functions and methods necessary to manipulate files by default. The file manipulation can be
done using a file object. The basic file operations are open, close, read and write files.
5.2 Problem Solving and Python Programming
The open Function
To read or write a file, it is necessary to open it using Python’s built-in function named
open() function. The open() function creates a file object that could be used to call other methods
associated with it. The syntax for open() function is shown below.
Syntax
fileobject = open(file_name [, access_mode][, buffering])
ab Opens a file for appending in binary format. The file pointer is at the end of the file if
the file exists. That is, the file is in the append mode. If the file does not exist, it creates
a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file if
the file exists. The file opens in the append mode. If the file does not exist, it creates a
new file for reading and writing.
ab+ Opens a file for both appending and reading in binary format. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If the file does not
exist, it creates a new file for reading and writing.
The file Object Attributes
Once a file is opened, there would be one file object, to get various information related to
that file.
Here is a list of all attributes related to file object:
Attribute Description
file.closed Returns true if the file is closed, otherwise false.
file.mode Returns the file access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with print, otherwise true.
The following illustrate the file attribute description using file object.
f = open(“file1.txt”, “w+”)
print “Name of the file: “, f.name
print “Closed or not : “, f.closed
print “Opening mode : “, f.mode
print “Softspace flag : “, f.softspace
Output:
Name of the file: file1.txt
Closed or not: False
Opening mode: w+
Softspace flag: 0
The close() Method
The function close() of a file object flushes, if there is any unwritten information and closes
the file object when there is no more writing is can be done. Python closes a file automatically when
the reference object of a file is reassigned with another file. It is a good practice to use the close ()
method to close a file. The syntax of close () function is given below.
5.4 Problem Solving and Python Programming
Syntax
fileObject.close();
Output:
Name of the file: file1.txt
The write() Method
The write() method is used to write any string to a file which is opened. Python strings can
have binary data and not just text. The write() method does not add a newline character (‘\n’) to the
end of the string. The syntax for write() function is shown below.
Syntax
fileObject.write(string);
The argument passed is the content to be written into the opened file. The following program
illustrates the file write operation.
f = open(“file1.txt”, “wb”)
print f
f.write( “Python is a programming language.\nIt is very flexible\n”);
# Close opened file
f.close()
Output:
open file ‘file1.txt’, mode ‘wb’ at 0xb7eb2410
Python is a programming language.
It is very flexible
The above program creates a file file1.txt and writes the given content in that file and finally
it closes that file. If the file is opened, then it would have content which was written.
Files, Modules, Packages 5.5
If the file already exists, then opening it in write mode erases the old data and starts fresh. If
the file doesn’t exist, then a new one is created.
For example,
line1 = “Python is a programming language, \n”
f.write (line1)
Here, the file object keeps track of where it is pointing to, so if write function is called again,
it adds the new data to the end of the file. For example,
line2 = “It is very flexible .\n”
f.write (line2)
If no more operations need to be performed, then the file could be closed using file close()
function.
f.close()
The read() Method
The file read() function reads the file contents from an open file. It is important to note that
Python strings can have binary data in addition to text data. The syntax for file read() is given below.
Syntax
fileObject.read([count]);
The argument passed is the number of bytes to be read from the opened file. This method
starts reading from the beginning of the file and if the argument count is missing, then it tries to read
as much as possible, till the end of file.
Example
To read from the file file1.txt
# Open a file
f=open(“file1.txt”, “w+”)
f.write(“ Python is a programming language”)
f.close()
f = open(“file1.txt”, “r+”)
str = f.read(20);
print “ The string read is : “, str
# Close opened file
f.close()
5.6 Problem Solving and Python Programming
Output:
The string read is : Python is a program
x = 52
f.write (str(x))
Here, the str function converts integer x value as string. An alternative way is to use the
format operator, %. When this is applied to integers, % is considered as the modulus operator. But
when the first operand is a string, % is considered as the format operator.
The first operand is the format string that contains one or more format sequences, to specify
how the second operand is formatted. The result is a string. For example, the format sequence ‘%d’
means that the second operand should be formatted as an integer (d stands for “decimal”): consider
the simple example.
x = 15
print ‘%d’ % x
Output:
15
The result is the string ‘15’, which is not to be confused with the integer value 15. A format
sequence can appear anywhere in the string, so you can embed a value in a sentence:
bugs= 10
print ‘I have spotted %d bugs.’ % bugs
Output:
I have spotted 10 bugs
If there is more than one format sequence in the string, the second argument must be a tuple.
Each format sequence is matched with an element of the tuple, in sequence. The various format
sequences are ‘%d’ to format an integer, ‘%g’ to format a floating-point number and ‘%s’ to format
a string.
Output:
In 2 years I have spotted 0.3 bugs.
The number of elements in the tuple has to match the number of format sequences in the
string. The types of the elements have to match the format sequences also.
Files, Modules, Packages 5.7
Example:
print ‘%d %d %d’ % (1, 2)
Output:
Traceback (most recent call last):
File “main.py”, line 1, in
print ‘%d %d %d’ % (1, 2)
TypeError: not enough arguments for format string
Example:
print ‘%d’ % ‘dollars’
Output:
Traceback (most recent call last):
File “main.py”, line 1, in
print ‘%d’ % ‘dollars’
TypeError: %d format: a number is required, not str
In the first example, there are three format sequences and only two elements; in the second,
the format sequence is for integer but the element is string. The format operator is more effective,
however it is difficult to use.
Method Description
close() Close an open file. It has no effect if the file is already closed.
Separate the underlying binary buffer from the TextIOBase
detach()
and return it.
fileno() Return an integer number (file descriptor) of the file.
flush() Flush the write buffer of the file stream.
isatty() Return True if the file stream is interactive.
Read atmost n characters form the file. Reads till end of file
read(n)
if it is negative or None.
readable() Returns True if the file stream can be read from.
Read and return one line from the file. Reads in at most n
readline(n=-1)
bytes if specified.
Read and return a list of lines from the file. Reads in at most
readlines(n=-1)
n bytes/characters if specified.
5.8 Problem Solving and Python Programming
File Positions
The tell() method gives the current object position within the file; In other words, the
next read or write will occur at that many bytes from the beginning of the file. The seek (offset
[, from]) method modifies the current file position. The offset argument specifies the number of
bytes to be moved. The from argument specifies the reference position from where the bytes are to
be moved. If from is set to 0, it means use the beginning of the file as the reference position and 1
means use the current position as the reference position and if it is set to 2 then the end of the file
would be taken as the reference position. The following program explains the functions of tell() and
seek() functions.
# Open a file
f=open(“file1.txt”, “w+”)
f.write(“ Python is a programming language”)
f.close()
f = open(“file1.txt”, “r+”)
str = f.read(20);
print “ The string read is : “, str
# Check current position
pos = f.tell();
print “current file position:”, pos
# reposition pointer at the beginning once again
pos = f.seek(0, 0)
str = f . read (10)
print “ Again the string read is: “, str
# close opened file
f . close()
Files, Modules, Packages 5.9
Output:
The string read is : Python is a program
Current file position : 20
Again the string read is : Python is
The remove() Method
The remove() method can be used to delete files by supplying the name of the file to be
deleted as the argument.
Syntax:
os.remove(file_name)
Example:
Following is the example to delete an existing file file2.txt −
import os
# Delete file file2.txt
os.remove(“file2.txt”)
os.mkdir(“test”)
The two files are opened in reading mode and iterate over each name using a for loop. A
new file with the name “[name].txt” is created, where name is the name of that person. Here, the
strip() method is used to clean up leading and trailing whitespaces (reading a line from the file
also reads the newline ‘\n’ character). Finally, we write the content of the mail into this file using
the write() method.
import sys
print ‘No. of arguments:’, len(sys.argv)
print ‘Argument List:’,str(sys.argv)
Run the above script as follows:
$ python test.py arg1 arg2 arg3
Files, Modules, Packages 5.11
Output:
Number of arguments: 4
Argument List: [‘test.py’, ‘arg1’,’arg2’,’arg3’]
Output:
/web/com/1493114533_4353
cwd stands for “current working directory.” The result in this example is /web/
com/1493114533_4353.
A string like cwd that identifies a file is called a path. A relative path starts from the current
directory; an absolute path starts from the topmost directory in the file system. The paths we have
seen so far are simple filenames, so they are relative to the current directory. To find the absolute
path to a file, you can use os.path.abspath:
abs_path=os.path.abspath(‘file1.txt’)
print abs_path
Output:
/web/com/1493114533_4353/file1.txt
os.path.exists checks whether a file or directory exists:
print os.path.exists(‘file1.txt’)
Output:
True
print os.path.isdir(‘file1.txt’)
Output:
False
5.12 Problem Solving and Python Programming
os.listdir returns a list of the files (and other directories) in the given directory:
>>> os.listdir(cwd)
[‘file1’, ‘file2’]
To demonstrate these functions, the following example “walks” through a directory, prints
the names of all the files, and calls itself recursively on all the directories.
def walk(dirname):
for name in os.listdir(dirname):
path = os.path.join(dirname, name)
if os.path.isfile(path):
print path
else:
walk(path)
os.path.join takes a directory and a file name and joins them into a complete path.
•• Syntax errors
•• Runtime errors
•• Logical errors
Syntax Errors
Syntax errors, also known as parsing errors are identified by Python while parsing the
program. It displays error message and exit without continuing execution process. They are similar
to spelling mistakes or grammar mistakes in normal language like English. Some common Python
syntax errors include:
•• leaving out a keyword
•• putting a keyword in the wrong place
•• leaving out a symbol, such as a colon, comma or brackets
•• misspelling a keyword
•• incorrect indentation
Files, Modules, Packages 5.13
•• empty block
Here are some examples of syntax errors in Python:
a=10
b=20
if a<b
print ‘a is greater’
Error Message:
File “main.py”, line 3
if a<b
^
SyntaxError: invalid syntax
The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest
point in the line where the error was detected. The error is caused by (or at least detected at) the
token preceding the arrow: in the example, the error is detected at the if a<b since a colon (‘:’) is
missing before it. File name and line number are printed so you know where to look in case the input
came from a script.
if True:
prnt ‘Hello’
Error Message:
File “main.py”, line 2
prnt ‘Hello’
^
SyntaxError: invalid syntax
In the above example, the error is detected at prnt ‘Hello’ since print is misspelled.
Logical errors
Logical errors occur due to mistake in program’s logic. Here program runs without any error
messages, but produces an incorrect result. These errors are difficult to fix. Here are some examples
of mistakes which lead to logical errors:
•• using the wrong variable name
•• indenting a block to the wrong level
•• using integer division instead of floating-point division
•• getting operator precedence wrong
•• making a mistake in a boolean expression
•• off-by-one, and other numerical errors
5.14 Problem Solving and Python Programming
Sample Output:
Fact:0
In this example for computing factorial of 5, the obtained output is 0. There are no syntax
errors. The wrong output occurs due to logical error fact=0. To compute factorial, the fact value
must be initialized to 1. As it is assigned as 0, it results in wrong output.
5.2.2 Exceptions
An exception is an error that occurs during execution of a program. It is also called as run
time errors. Some examples of Python runtime errors:
•• division by zero
•• performing an operation on incompatible types
•• using an identifier which has not been defined
•• accessing a list element, dictionary value or object attribute which doesn’t exist
•• trying to access a file which doesn’t exist
Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong. When these exceptions occur, it stops the current process and passes the
control to corresponding exception handler. If not handled, our program will crash.
Handling Exceptions
The simplest way to handle exceptions is with a “try-except” block. Exceptions that are
caught in try blocks are handled in except blocks. The exception handling process in Python is
shown in Figure.5.1. If an error is encountered, a try block code execution is stopped and control
transferred down to except block.
5.16 Problem Solving and Python Programming
Syntax:
try:
# statements
break
except ErrorName:
# handler code
(x,y) = (5,0)
try:
z = x/y
except ZeroDivisionError:
print “divide by zero”
Sample Output:
divide by zero
To display built-in error message of exception, you could have :
(x,y) = (5,0)
try:
z = x/y
Files, Modules, Packages 5.17
except ZeroDivisionError as e:
z = e # representation: “<exceptions.ZeroDivisionError instance at 0x817426c>”
print z # output: “integer division or modulo by zero”
Sample Output:
integer division or modulo by zero
A try statement may have more than one except clause, to specify handlers for different
exceptions. If an exception occurs, Python will check each except clause from the top down to see
if the exception type matches. If none of the except clauses match, the exception will be considered
unhandled, and your program will crash:
Syntax:
try:
# statements
break
except ErrorName1:
# handler code
except ErrorName2:
# handler code
A simple example to handle multiple exceptions is as follows.
try:
dividend = int(input(“Please enter the dividend: “))
divisor = int(input(“Please enter the divisor: “))
print(“%d / %d = %f” % (dividend, divisor, dividend/divisor))
except ValueError:
print(“The divisor and dividend have to be numbers!”)
except ZeroDivisionError:
print(“The dividend may not be zero!”)
An except clause may name multiple exceptions as a parenthesized tuple, for example:
... except (RuntimeError, TypeError, NameError):
Example:
try:
dividend = int(input(“Please enter the dividend: “))
divisor = int(input(“Please enter the divisor: “))
print(“%d / %d = %f” % (dividend, divisor, dividend/divisor))
except(ValueError, ZeroDivisionError):
print(“Oops, something went wrong!”)
Sample Input/Output:
Please enter the dividend: 10
Please enter the divisor: 0
Oops, something went wrong!
To catch all types of exceptions using single except clause, simply mention except keyword
without specifying error name. It is shown in following example.
try:
dividend = int(input(“Please enter the dividend: “))
divisor = int(input(“Please enter the divisor: “))
print(“%d / %d = %f” % (dividend, divisor, dividend/divisor))
except:
print(“Oops, something went wrong!”)
Raising Exceptions
The raise statement initiates a new exception. It allows the programmer to force a specified
exception to occur. The raise statement does two things: it creates an exception object, and
Files, Modules, Packages 5.19
immediately leaves the expected program execution sequence to search the enclosing try statements
for a matching except clause. It is commonly used for raising user defined exceptions. Two forms
of the raise statement are:
Syntax:
raise ExceptionClass(value)
raise Exception
Example:
try:
raise NameError
except NameError:
print(‘Error’)
Sample Output:
Error
raise without any arguments is a special use of python syntax. It means get the exception
and re-raise it. The process is called as reraise. If no expressions are present, raise re-raises the last
exception that was active in the current scope.
Example:
try:
raise NameError
except NameError:
print(‘Error’)
raise
Sample Output:
Error
Traceback (most recent call last):
File “main.py”, line 2, in <module>
raise NameError(‘Hi’)
NameError: Hi
In the example, raise statement inside except clause allows you to re-raise the exception
NameError.
try:
age = int(input(“Please enter your age: “))
except ValueError:
print(“Hey, that wasn’t a number!”)
else:
print(“I see that you are %d years old.” % age)
Sample input/output:
Please enter your age: 10
I see that you are 10 years old.
Please enter your age: ‘a’
Hey, that wasn’t a number!
In addition to using except block after the try block, you can also use the finally block. The
code in the finally block will be executed regardless of whether an exception occurs and even if we
exit the block using break, continue, or return.
try:
age = int(input(“Please enter your age: “))
except ValueError:
print(“Hey, that wasn’t a number!”)
else:
print(“I see that you are %d years old.” % age)
finally:
print(“Goodbye!”)
Sample input/output:
Please enter your age: 20
I see that you are 20 years old.
Goodbye!
Sample input/output:
Enter a number: 12
This value is positive!
In the example, the user defined exception class Error is derived from built-in class
Exception. It handles two user defined exceptions: PosError, raised when input value is positive
and NegError, raised when input value is negative. The pass keyword indicates null block. The
main program reads user input and compares input value with 0. If input>0, the exception PosError
is raised using raise keyword else the exception NegError is raised.
5.3 MODULES
A Python module is a file that consists of Python code. It allows us to logically arrange
related code and makes the code easier to understand and use. It defines functions, classes and
variables.
5.22 Problem Solving and Python Programming
Python has many useful functions and resources in modules. Functions such as abs() and
round() from __builtin__ module are always directly accessible in every Python code. But, the
programmer must explicitly import other functions from the modules in which they are defined.
import statement
An import statement is used to import Python module in some Python source file.
Example:
import math
For example, math is a built-in module that offers several built-in functions for carrying out
basic mathematical operations. The following code imports math module and lists a directory of its
resources:
import math
print dir(math)
Output:
[‘__doc__’, ‘__file__’, ‘__name__’, ‘__package__’, ‘acos’, ‘acosh’, ‘asin’, ‘asinh’,
‘atan’, ‘atan2’, ‘atanh’, ‘ceil’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’, ‘e’, ‘erf’, ‘erfc’,
‘exp’, ‘expm1’, ‘fabs’, ‘factorial’, ‘floor’, ‘fmod’, ‘frexp’, ‘fsum’, ‘gamma’,
‘hypot’, ‘isinf’, ‘isnan’, ‘ldexp’, ‘lgamma’, ‘log’, ‘log10’, ‘log1p’, ‘modf’, ‘pi’,
‘pow’, ‘radians’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘trunc’]
The usage of some built-in functions of math module is shown in the following code along
with its output:
import math # Import built-in module math
print math.floor(6.9)
print math.ceil(6.9)
print math.pow(3,4)
Output:
6.0
7.0
81.0
Files, Modules, Packages 5.23
support.py
def add( a, b ):
print ‘Result is ‘, a+b
return
def display(p):
print ‘Welcome, ‘,p
return
This support.py file can be imported as a module in another Python source file and its
functions can be called from the new file as shown in the following code:
import support # Import module support
support.add(3,4) # calling add() of support module with two integer values
support.add(3.5,4.7) # calling add() of support module with two real values
support.add(‘a’,’b’) # calling add() of support module with two character values
support.add(‘Ram’,’Kumar’) # calling add() of support module with two string values
support.display(‘Ram’) # calling display() of support module with a string value
5.24 Problem Solving and Python Programming
from...import Statement
It allows us to import specific attributes from a module into the current namespace.
Syntax:
from modulename import name1[, name2[, ... nameN]]
The first statement of the following code does not import the entire module support into the
current namespace; it just introduces the item add from the module support into the global symbol
table of the importing module. Hence, a call to display() function generates an error as shown in the
output.
from support import add # Import module support
add(3,4) # calling add() of support module with two integer values
add(3.5,4.7) # calling add() of support module with two real values
add(‘a’,’b’) # calling add() of support module with two character values
add(‘Ram’,’Kumar’) # calling add() of support module with two string values
display(‘Ram’) # calling display() of support module with a string value
Output:
Result is 7
Result is 8.2
Result is ab
Result is RamKumar
Traceback (most recent call last):
File “main.py”, line 8, in
display(‘Ram’) # calling display() of support module with a string value
NameError: name ‘display’ is not defined
Files, Modules, Packages 5.25
from...import * Statement:
It allows us to import all names from a module into the current namespace.
Syntax:
from modulename import *
Sample Code:
from support import * # Import module support
add(3,4) # calling add() of support module with two integer values
add(3.5,4.7) # calling add() of support module with two real values
add(‘a’,’b’) # calling add() of support module with two character values
add(‘Ram’,’Kumar’) # calling add() of support module with two string values
display(‘Ram’) # calling display() of support module with a string value
Sample Output:
Result is 7
Result is 8.2
Result is ab
Result is RamKumar
Welcome, Ram
Programs that will be imported as modules often use the following expression:
if __name__ == ‘__main__’:
# test code
Here, __name__ is a built-in variable and is set when the program starts execution. If the
program runs as a script, __name__ has the value __main__ and the test code is executed. Else, the
test code is skipped.
Sample Code:
from support import * # Import module support
if __name__ == ‘__main__’: # add() and display() are called only if this pgm runs as
a script.
add(3,4)
display(‘Ram’)
Sample Output:
Result is 7
Welcome, Ram
reload()
5.26 Problem Solving and Python Programming
When the module is already imported into a script, the module is not re-read eventhough it
is modified. The code of a module is executed only once. To reload the previously imported module
again, the reload() function can be used.
Syntax:
reload(modulename)
print(“Welcome”)
5.4 PACKAGES
When we have a large number of Python modules, they can be organized into
packages such that similar modules are placed in one package and different modules are
placed in different packages. A package is a hierarchical file directory structure that defines a
single Python application environment that consists of modules, sub-packages, sub-subpackages,
and so on. In another words, it is a collection of modules. When a package is imported, Python
explores in list of directories on sys.path for the package subdirectory.
Example:
Assume we are creating a package named Animals with some subpackages as shown in
Figure.5.2.
Animals
(Package)
_init_.py _init_.py
(Module) (Module)
create.py create.py
(Module) (Module)
print.py display.py
(Module) (Module)
Method 1:
Consider, we import the display.py module in the above example. It is accomplished by the
following statement.
5.28 Problem Solving and Python Programming
import Animals.Birds.display
Method 2:
On another way, we can import display.py module alone as follows:
from Animals.Birds import display
Then, we can call displayByName() function simply as shown in the following statement:
display.displayByName()
Method 3:
In the following statement, the required function alone is imported from a module within a
package:
from Animals.Birds.display import displayByName
Though this method is simple, usage of full namespace qualifier avoids confusion and
prevents two similar identifier names from colliding.
In the above example, __init__.py of Animals package contains the following code:
from Mammals import Mammals
from Birds import Birds
In python, module is a single Python file and package is a directory of Python modules
containing an additional __init__.py file. Packages can be nested to any depth, but the
corresponding directories should include their own __init__.py file.
5.5.2 Python program to raise an exception when the user input is negative
try:
a = int(input(“Enter a positive integer value: “))
if a <= 0:
raise ValueError(“This is not a positive number!!”)
except ValueError as ve:
print(ve)
Sample input:
Enter a positive integer value: -1
Error:
This is not a positive number!!
wordcount[word] = 1
else:
wordcount[word] += 1
for k,v in wordcount.items():
print k, v
file.close()
Sample Output:
This 1
program 2
example 1
Python 2
Program 2:
with open(“in.txt”) as f:
with open(“out.txt”, “w”) as f1:
for line in f:
if “ROW” in line:
f1.write(line)
Program 3:
# The shutil module offers a number of high-level operations on files and collections
of files
from shutil import copyfile
copyfile(‘test.py’, ‘abc.py’) # copy content of test.py to abc.py
Files, Modules, Packages 5.31
5.6.6 Python program to append text to a file and display the text
def file_read(fname):
with open(fname, “w”) as myfile:
myfile.write(“Python Exercises\n”)
myfile.write(“Java Exercises”)
txt = open(fname)
print(txt.read())
file_read(‘abc.txt’)
Sample Output:
Python Exercises
Java Exercises
Random access file - Python program to read a random line from a file.
A random-access data file enables you to read or write information anywhere in the file.
You can use seek() method to set the file marker position and tell() method to get the current
position of the file marker. In a sequential-access file, you can only read and write information
sequentially, starting from the beginning of the file.
f=open(‘Python_source\\test.txt’,’w’)
f.write(‘DearChanna ‘)
f.seek(4) #move file pointer to 4th position from beginning of file
f.write(‘ Mr.Channa’)
f.close()
f=open(‘Python_source\\test.txt’,’r’)
f.read()
Sample Output:
Dear Mr.Channa
5.32 Problem Solving and Python Programming
Program that asks the user to input customer information, call writetofile method to
write data to the file and call getall method to retrieve customer information from file.
#write data to file
def writetofile(Name,Email=’’,Tel=’’,Address=’’):
try:
f=open(r’customerlist.txt’,’a’)
f.write(Name+’:’+Email+’:’+Tel+’:’+Address+’\n’)
except Exception:’Print error in writing to file...’
finally:
f.flush()
f.close()
#Get all customers’information and display
def getall():
f=open(r’customerlist.txt’,’r’)#open file for reading
content=f.readlines()#read all lines
f.close()
return content
def add():
Name=raw_input(‘Name:’)
Email=raw_input(‘Email:’)
Tel=raw_input(‘Tel:’)
Address=raw_input(‘Address:’)
writetofile(Name,Email,Tel,Address)
#main program
add()
print getall()
With reference to previous program, write a method to search for a customer by name.
#Search customer by name. If match is found, it returns the position of the name else
returns -1.
def search(Name):
global flag#declare global variable
try:
f=open(r’customerlist.txt’,’r’)#open file for reading
Files, Modules, Packages 5.33
f.seek(0)
content=f.readline()
while content!=’’:
if content.find(Name)!=-1:
print content
flag=1
return int(f.tell())-int(len(content)+1) # return the position of the matched name
else:
content=f.readline()
flag=0
except Exception:print ‘Error in reading file...’
finally:
f.close()
if flag==0:
print ‘Not found’ #Inform the use if the record does not exist
return -1 # The record not found-->return -1
Using previous search method, write a program to delete a customer name from file.
#delete customer’s information by name
def delete(Name):
print search(Name)
p=search(Name) # returns position of given customer name
print “x=”,p
if p!=-1: #Make sure the record exists
st=getall() #retrieve content about cutomer
f=open(r’customerlist.txt’,’w’)#open file for writing
f.writelines(st)
f.seek(p)
f.write(‘*****’)#write 5 starts to override the 5 characters of the name to be
deleted
else:
print ‘No record to delete’#Inform the use if the record does not exist
f.close()
PROBLEM SOLVING AND PYTHON
PROGRAMMING LABORATORY
TABLE OF CONTENTS
Ex.
DATE NAME OF THE EXPERIMENT PAGE No. MARKS SIGNATURE
No.
1. Compute the GCD of two numbers. App-A.1
2. Find the square root of a number App-A.2
(Newton’s method)
3. Exponentiation (power of a number) App-A.3
4. Linear search and Binary search App-A.4
5. First n prime numbers App-A.6
6. Find the maximum of a list of App-A.7
numbers
7. Selection sort, Insertion sort App-A.9
8. Removing all the duplicate elements App-A.12
in a list
9. Merge sort, Quick sort App-A.14
10. Multiply Matrices App-A.18
11. Programs that take command line App-A.20
arguments (word count)
12. Find the most frequent words in a App-A.21
text read from a file
APPENDIX - A
LAB PROGRAMS
Aim
To write an python program to find the Greatest Common Divisor of any two positive
integers.
Algorithm
Program
a=int(input("x value="))
b=int(input("y value="))
def gcd(x, y):
gcd = 1
if x % y == 0:
return y
Result:
Thus the above program was executed successfully and output was verified.
App-A.2 Problem Solving and Python Programming
Aim
To write an python program to find the squre root of a given positive integer.
Algorithm
Program
while True:
print("Enter 'x' for exit.")
num = input("Enter a number: ")
if num == 'x':
break
else:
number = float(num)
number_sqrt = number ** 0.5
print("Square Root of %0.3f is %0.3f" %(number, number_sqrt))
Output:
Enter 'x' for exit.
Enter a number: 3
Square Root of 3.000 is 1.732
Enter 'x' for exit.
Enter a number: 16
Square Root of 16.000 is 4.000
Enter 'x' for exit.
Enter a number: x
Result:
Thus the above program was executed successfully and output was verified.
Appendix -A Lab Programs App-A.3
Aim
To write an python program to find the exponentiation of a given positive integer.
Algorithm
Program
import math
a=float(input("Enter a value"))
print("The exponential value of {0} is ".format(a),math.exp(a))
Output
Enter a value100.12
The exponential value of 100.12 is 3.03084361407e+43
Result:
Thus the above program was executed successfully and output was verified.
App-A.4 Problem Solving and Python Programming
Aim
To write an python program to perform linear search and binary search.
Algorithm
Program
Linear Search
def linearSearch(myItem,myList):
found = False
position = 0
while position < len(myList) and not found:
if myList[position] == myItem:
found = True
position = position +1
return found
if __name__=="__main__":
shopping=["Apple","Banana","Orange","Guvava","Pienapple","Bread","Milk"]
item = input("Enter your item to search: ")
isitFound = linearSearch(item,shopping)
if isitFound:
print("Your item is in the list")
else:
print("Sorry your item not in the list")
Output:
Enter your item to search: Apple
Your item is in the list
Enter your item to search: Butter
Sorry your item not in the list
Binary Search
def binarySearch(myItem,myList):
found = False
Appendix -A Lab Programs App-A.5
bottom = 0
top = len(myList) - 1
while bottom <= top and not found:
middle = (bottom+top)//2
if myList[middle] == myItem:
found = True
elif myList[middle] < myItem:
bottom = middle + 1
else:
top = middle-1
return found
if __name__=="__main__":
numberList=[1,3,4,8,69,45,32,46,78,20,25,46,10,75,36,99,100]
number = int(input("Enter your number to search: "))
isitFound = binarySearch(number,numberList)
if isitFound:
print("The entered number {0} is in the list".format(number))
else:
print("The entered number {0} is not in the list".format(number))
Output:
Enter your number to search: 45
The entered number 45 is in the list
Enter your number to search: 1000
The entered number 1000 is not in the list
Result
Thus the above program was executed successfully and output was verified.
App-A.6 Problem Solving and Python Programming
Output
Enter the number:50
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
Result
Thus the above program was executed successfully and output was verified.
Appendix -A Lab Programs App-A.7
Aim
To write an python program to find the maximum of a list of numbers.
Algorithm
Program
def highestNumber(l):
myMax = l[0]
for num in l:
if myMax < num:
myMax = num
return myMax
list=[]
while True:
print("Enter '-1' for exit.")
list1=int(input("Enter a number: "))
if list1 == -1:
break
else:
list.append(list1)
Result
Thus the above program was executed successfully and output was verified.
Appendix -A Lab Programs App-A.9
Aim
To write an python program to perform Selection sort and Insertion sort.
Algorithm
Program
Selection Sort
def selectionSort(nlist):
for fillslot in range(len(nlist)-1,0,-1):
maxpos=0
for location in range(1,fillslot+1):
if nlist[location]>nlist[maxpos]:
maxpos = location
temp = nlist[fillslot]
nlist[fillslot] = nlist[maxpos]
nlist[maxpos] = temp
nlist = []
while True:
print("Enter '-1' for exit.")
list1=int(input("Enter a number: "))
if list1 == -1:
break
else:
nlist.append(list1)
print("The created list is \n",nlist)
selectionSort(nlist)
print("The sorted elements are",nlist)
Output
Enter '-1' for exit.
Enter a number: 2
Enter '-1' for exit.
App-A.10 Problem Solving and Python Programming
Enter a number: 3
Enter '-1' for exit.
Enter a number: 4
Enter '-1' for exit.
Enter a number: 69
Enter '-1' for exit.
Enter a number: 100
Enter '-1' for exit.
Enter a number: 65
Enter '-1' for exit.
Enter a number: 78
Enter '-1' for exit.
Enter a number: 60
Enter '-1' for exit.
Enter a number: -1
The created list is
[2, 3, 4, 69, 100, 65, 78, 60]
The sorted elements are [2, 3, 4, 60, 65, 69, 78, 100]
Insertion sort
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = []
while True:
print("Enter '-1' for exit.")
list1=int(input("Enter a number: "))
if list1 == -1:
Appendix -A Lab Programs App-A.11
break
else:
alist.append(list1)
print("The created list is \n",alist)
insertionSort(alist)
print("The sorted elements are",alist)
Output
Enter '-1' for exit.
Enter a number: 23
Enter '-1' for exit.
Enter a number: 10
Enter '-1' for exit.
Enter a number: 60
Enter '-1' for exit.
Enter a number: 1
Enter '-1' for exit.
Enter a number: 8
Enter '-1' for exit.
Enter a number: 3
Enter '-1' for exit.
Enter a number: -1
The created list is
[23, 10, 60, 1, 8, 3]
The sorted elements are [1, 3, 8, 10, 23, 60]
Result
Thus the above program was executed successfully and output was verified.
App-A.12 Problem Solving and Python Programming
Aim
To write an python program to remove all the duplicate elements in a list.
Algorithm
Program
def removeDuplicate(alist):
print("Before eliminating duplicate entries in the list",alist)
rlist=list(set(alist))
print("After eliminating duplicate entries in the list",rlist)
alist = []
while True:
print("Enter 'x' for exit.")
list1=input("Enter a number: ")
if list1 == 'x':
break
else:
alist.append(list1)
print("The created list is \n",alist)
removeDuplicate(alist)
Output
Enter 'x' for exit.
Enter a number: 5
Enter 'x' for exit.
Enter a number: 6
Enter 'x' for exit.
Enter a number: 5
Enter 'x' for exit.
Enter a number: 2
Enter 'x' for exit.
Enter a number: 2
Appendix -A Lab Programs App-A.13
Result
Thus the above program was executed successfully and output was verified.
App-A.14 Problem Solving and Python Programming
Aim
To write an python program to implement merge sort and quick sort.
Algorithm
Program
Merge Sort
def merge(a,b):
""" Function to merge two arrays """
c = []
while len(a) != 0 and len(b) != 0:
if a[0] < b[0]:
c.append(a[0])
a.remove(a[0])
else:
c.append(b[0])
b.remove(b[0])
if len(a) == 0:
c += b
else:
c += a
return c
def mergeSort(alist):
""" Function to sort an array using merge sort algorithm """
if len(alist) == 0 or len(alist) == 1:
return alist
else:
middle = len(alist)//2
a = mergeSort(alist[:middle])
b = mergeSort(alist[middle:])
return merge(a,b)
alist = []
Appendix -A Lab Programs App-A.15
while True:
print("Enter '-1' for exit.")
list1=int(input("Enter a number: "),10)
if list1 == -1:
break
else:
alist.append(list1)
Output
Enter '-1' for exit.
Enter a number: 36
Enter '-1' for exit.
Enter a number: 62
Enter '-1' for exit.
Enter a number: 89
Enter '-1' for exit.
Enter a number: 1
Enter '-1' for exit.
Enter a number: 325
Enter '-1' for exit.
Enter a number: 63
Enter '-1' for exit.
Enter a number: 55
Enter '-1' for exit.
Enter a number: 87
Enter '-1' for exit.
Enter a number: -1
The created list is
[36, 62, 89, 1, 325, 63, 55, 87]
After doing merge sort
[1, 36, 55, 62, 63, 87, 89, 325]
App-A.16 Problem Solving and Python Programming
Quick Sort
def quickSort(myList, start, end):
if start < end:
# partition the list
pivot = partition(myList, start, end)
# sort both halves
quickSort(myList, start, pivot-1)
quickSort(myList, pivot+1, end)
return myList
alist = []
while True:
print("Enter '-1' for exit.")
Appendix -A Lab Programs App-A.17
Output
Enter '-1' for exit.
Enter a number: 23
Enter '-1' for exit.
Enter a number: 56
Enter '-1' for exit.
Enter a number: 41
Enter '-1' for exit.
Enter a number: 20
Enter '-1' for exit.
Enter a number: 63
Enter '-1' for exit.
Enter a number: 45
Enter '-1' for exit.
Enter a number: 10
Enter '-1' for exit.
Enter a number: 1
Enter '-1' for exit.
Enter a number: 3
Enter '-1' for exit.
Enter a number: -1
The created list is
[23, 56, 41, 20, 63, 45, 10, 1, 3]
After doing merge sort
[1, 3, 10, 20, 23, 41, 45, 56, 63]
Result
Thus the above program was executed successfully and output was verified.
App-A.18 Problem Solving and Python Programming
Aim
To write an python program to implement multiplication of N X N Matrices.
Algorithm
Program
matrixA = []
matrixB = []
print("Enter the value of N for N x N:")
N = int(input())
print("Enter the elements of matrix A:")
for i in range(N):
matrixA.append(input().split())
print("Enter the elements of matrix B:")
for i in range(N):
matrixB.append(input().split())
15
22
Result
Thus the above program was executed successfully and output was verified.
App-A.20 Problem Solving and Python Programming
Aim
To write an python program to implement a program that take command line arguments.
Algorithm
Program – Can able to execute in ubuntu
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
Output
vctw@vctwcsevb:~/Desktop/cmdline$ python cmdlinearg.py 1
10
Result
Thus the above program was executed successfully and output was verified.
Appendix -A Lab Programs App-A.21
Aim
To write an python program to implement a program to find the most frequent words in a
text read from a file.
Algorithm
Program
from string import punctuation
from operator import itemgetter
wordsCount=0
words = {}
words_gen = (word.strip(punctuation).lower() for line in open("D:\\S\\test.txt")
for word in line.split())
for word in words_gen:
words[word] = words.get(word, 0) + 1
wordsCount +=1
top_words = sorted(words.items(), key=itemgetter(1), reverse=True)[:wordsCount]
print("Number of Words in the given text File: ",wordsCount)
print("Words frequencies are: ")
print("=======================")
for word, frequency in top_words:
print("%s: %d" % (word, frequency))
Output
Number of Words in the given text File: 31
Words frequencies are:
=======================
and: 4
a: 2
programming: 2
features: 1
dynamic: 1
App-A.22 Problem Solving and Python Programming
it: 1
library: 1
including: 1
management: 1
system: 1
imperative: 1
memory: 1
has: 1
supports: 1
styles: 1
multiple: 1
python: 1
comprehensive: 1
functional: 1
standard: 1
paradigms: 1
type: 1
large: 1
object-oriented: 1
automatic: 1
procedural: 1
Result
Thus the above program was executed successfully and output was verified.
APPENDIX - B
UNIT – I
ALGORITHMIC PROBLEM SOLVING
PART-A
1. Define Algorithm
Algorithm : It is a sequence of instructions designed in such a way that if the instructions are
executed in the specified sequence, the desired results will be obtained. The instructions in an
algorithm should not be repeated infinitely. The algorithm should be written in sequence.
Selection:
A selection (also called a decision) is also one of the basic logic structures in computer
programming. In a selection structure, a question is asked, and depending on the answer, the
program takes one of two courses of action, after which the program moves on to the next
event.
App-B.2 Problem Solving and Python Programming
Selection:
A selection (also called a decision) is also one of the basic logic structures in computer
programming. In a selection structure, a question is asked, and depending on the answer, the
program takes one of two courses of action, after which the program moves on to the next
event.
5. Define Flowchart
It is a pictorial representation of an algorithm. The flowchart uses different shape symbols to
denote the different appropriate instructions and these instructions can be written within the
boxes using clear statements.
2. Algorithms can be described in various ways, Pseudo code describes how you would
from pure mathematical formulas to complex implement an algorithm without getting
graphs into syntactical details.
PART-B
1. Define algorithm. Explain in detail about the building blocks of algorithm.
2. What is flowchart. Explain the Basic design structures in Flowchart
3. What is pseudo code? Explain its guidelines and benefits
4. Explain the design structures in pseudo code.
5. Explain the steps involved in program development cycle
6. Write the algorithm, pseudocode and draw the flowchart for the following:
(a) Find minimum in a list
(b) Insert a card in a list of sorted cards
(c) Guess an integer number in a range
(d) Towers of Hanoi
7. Write the algorithm, pseudocode and draw the flowchart for the following:
(a) To find the sum of square root of any three numbers.
(b) To find the sum of first 100 integers.
(c) To find the sum of all odd numbers till 100.
(d) To find the sum of any five integers.
(e) To find the factorial of number n.
(f) To find the first n numbers in a Fibonacci series.
(g) To find the sum of digits of a number
(h) To find whether a number is prime or not.
(i) To convert temperature from Fahrenheit to Celsius.
(j) To solve the quadratic equation.
(k) To find sum first 100 natural numbers.
(l) To find factorial of a number.
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.5
UNIT - II
DATA, EXPRESSIONS AND STATEMENTS
PART A
1. Define python
Python is an object-oriented, high level language, interpreted, dynamic and multipurpose
programming language.
10. What is tuple ? What is the difference between list and tuple?
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be
updated. Tuples can be thought of as read-only lists.
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.7
Eg:
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same object) x is not True
PART - B
UNIT – III
CONTROL FLOW AND FUNCTIONS
PART A
Syntax:
while <expression>: Body
10. What is len function and explain how it is used on strings with an example.
The len function, when applied to a string, returns the number or character in a string.
Example:
>>>book=’Problem Solving and Python Programming’
>>>len(book) 38
>>>
12. What are the two operators that are used in string functions?
The in operator tests for membership.
>>>’V’ in ‘VRB’
True
>>>’S’ in ‘VRB’
>>>False
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.13
15. How to split strings and what function is used to perform that operation?
The str.split() method is used to split strings up.
>>>book=’Problem Solving and Python Programming’
>>>print(book.split())
[‘Problem’, ‘Solving’, ‘and’, ‘Python’, ‘Programing’]
PART – B
Assuming num=125, determine the value of each of the following Python expressions.
(8 marks)
(i) num/125
(ii) num%100
(iii) (num==21)&(2<3)
(iv) not((num<45.9)&(6*2<=13))
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.15
UNIT – IV
COMPOUND DATA: LIST, TUPLE, DICTIONARY
PART –A
10. What is the output of print tuple[1:3] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
In the given command, tuple[1:3] is accessing the items in tuple using indexing.
It will print elements starting from 2nd till 3rd. Output will be (786, 2.23).
11. What are the methods that are used in Python Tuple?
Methods that add items or remove items are not available with tuple. Only the following two
methods are available:
(a) count(x)- returns the number of items that is equal to x
(b) index(x)- returns index of first item that is equal to x
>>>a<
b True
13. What are the built-in functions that are used in Tuple?
•• all()- returns true if all elements of the tuple are true or if tuple is empty
•• any()- returns true if any element of tuple is true
•• len()- returns the length in the tuple
•• max()- returns the largest item in tuple
•• min()- returns the smallest item in tuple
•• sum()- returns the sum of all elements in tuple
14. What is the output of print tuple + tinytuple if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) and
tinytuple = (123, 'john')?
It will print concatenated tuples. Output will be ('abcd', 786, 2.23, 'john', 70.200000000000003,
123, 'john').
19. Explain values and items method used in dictionary with example.
The values method is similar; it returns a list of the values in the dictionary:
>>>
eng2sp.values() [’uno’, ’tres’, ’dos’]
The items method returns both, in the form of a list of tuples—one for each key-value pair:
>>> eng2sp.items()
[(’one’,’uno’), (’three’, ’tres’), (’two’, ’dos’)]
The syntax provides useful type information. The square brackets indicate that this is a list. The
parentheses indicate that the elements of the list are tuples.
20. What is the difference between modify and copy operations performed in dictionary?
If you want to modify a dictionary and keep a copy of the original, use the copy method. For
example, opposites is a dictionary that contains pairs of opposites:
>>> opposites = {’up’: ’down’, ’right’: ’wrong’, ’true’: ’false’}
>>> alias = opposites
>>> copy = opposites.copy()
alias and opposites refer to the same object; copy refers to a fresh copy of the same dictionary.
If we modify alias, opposites is also changed:
>>> alias[’right’] = ’left’
>>>
opposites[’right’] ’left’
If we modify copy, opposites is unchanged:
>>> copy[’right’] = ’privilege’
>>> opposites[’right’] ’left
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.19
PART – B
4. What are the basic list operations that can be performed in Python? Explain each
operation with its syntax and example. (16 marks)
5. What is Dictionary? Explain Python dictionaries in detail discussing its operations and
methods. (16 marks)
App-B.20 Problem Solving and Python Programming
UNIT – V
FILES, MODULES AND PACKAGES
PAR T – A
>>> print f<open file ‘test.dat’, mode ‘w’ at fe820> The open function takes two arguments.
The first is the name of the file, and the second is the mode. Mode "w" means that we are opening
the file for writing.
Closing the file tells the system that we are done writing and makes the file available for
reading:
>>> f.close()
Appendix -B Two Mark and 16 Mark Questions with Answers App-B.21
6. Which method is used to read the contents of a file which is already created?
The read method reads data from the file. With no arguments, it reads the entire contents of the
file:
>>> text = f.read()
>>> print text
Now is the timeto close the file
For example,
dividing by zero creates an exception:
>>> print 55/0
ZeroDivisionError: integer division or modulo So does accessing a nonexistent list item:
>>> a = []
>>> print a[5]
IndexError: list index out of range Or accessing a key that isn’t in the dictionary:
>>> b = {}
>>> print b[’what’] KeyError: what
12. List some few common Exception types and explain when they occur.
ArithmeticError- Base class for all errors that occur for numeric calculations.
OverflowError- Raised when a calculation exceeds maximum limit for a numeric type.
ZeroDivisionError- Raised when division or modulo by zero takes place. ImportError- Raised
when an import statement fails.
IndexError- Raised when an index is not found in a sequence.
RuntimeError- Raised when a generated error does not fall into any category.
PART – B
1) Answer the following questions.
(a) Write a small code to illustrate try and except statements in Python. (4 marks)
(b) What are packages? Give an example of package creation in Python. (4 marks)
(c) Compare and contrast Extending and Embedding Python. (4 marks)
(d) Write an algorithm to check whether a student is pass or fail, the total marks of stu-
dent being the input. (4 marks)
2) Answer the following questions.
(a) Write a program to enter a number in Python and print its octal and hexadecimal
equivalent. (6 marks)
(b) Demonstrate the use of Exception Handling in Python.(10 marks)
3) Answer the following questions.
(a) What are modules in Python? Explain. (4 marks)
(b) Explain in details about namespaces and scoping. (8 marks)
(c) Explain about the import statement in modules. (4 marks)
4) Answer the following questions.
(a) Explain about the different types of Exceptions in Python. (6 marks)
(b) Describe about Handling Exceptions in detail with examples. (10 marks)
5) Explain in detail about Python Files, its types, functions and operations that can be
performed on files with examples. (16 marks)
APPENDIX - C
PREVIOUS YEAR
UNIVERSITY QUESTION PAPER
b) Explain with relevant diagrams and algorithm the Towers of Hanoi problem. (16)
12. a) i) Explain with an example the structure of a Python program. (8)
App-C.2 Problem Solving and Python Programming
ii) Outline with an example the assignment operators supported in Python. (8)
(OR)
b) Explain the various data types in Python. (16)
13. a) i) Write a Python program using while loop to print the first n numbers divisible
by 5. (8)
ii) Write a Python program to compute the factorial of a given number. (8)
(OR)
b) Write Python program to perform binary search. (16)
14. a) Write code snippets in Python to perform the following :
i) Accessing elements of a tuple. (5)
ii) Modifying elements of a tuple. (5)
iii) Deleting elements of a tuple. (6)
(OR)
b) Write the Python program to sort an integer list using selection sort. (16)
15. a) Describe in detail how exceptions are handled in Python. Give relevant examples. (16)
(OR)
b) Write a Python program to copy the contents of one file to another. (16)
———————