GE8151 - PSPP - Question Bank With Answers PDF
GE8151 - PSPP - Question Bank With Answers PDF
GE8151 - PSPP - Question Bank With Answers PDF
QUESTION BANK
(NOTE: THIS IS PURELY BASED ON ANNA UNIVERSITY QUESTION PAPERS FOR
THE YEAR DEC/JAN ’19, JAN ’18, APR/MAY ’19 ONLY, NOT COMPLETE SYLLABUS)
UNIT - 1
PART A
Algorithm Program
Algorithm is aSystematic logical Program is exact code written for
approach which is a well-defined, problem following all the rules of the
step-by-step procedure that allows programming language.
a computer to solve a problem.
Example Example
Step 1: Start print(“Welcome”)
Step 2: Print “Welcome”
Step 3: End
Algorithm:
Step 1: Start
Step 2 : Read list of n elements
Step 3: Assign min= list [0]
Step 3 :for i in range 1 to n, repeat step 4
Step 4: list [i] < min then min=list [i]
Step 5: return min
Step 6: Stop
1
4. Write an algorithm to accept two numbers, compute the sum and print the result.(Jan ’18)
STEP 1: Start
STEP 2: Read a
STEP 3: Read b
STEP 4: c=a+b
STEP 5: Write c
STEP 6: Stop
2
8. Give the python code to find the minimum among the list of 10 numbers.(April/May-19)
list=[2,4,56,27,89,100,23,44,55,67]
min=list[0]
for i in range(0,len(list)):
if (list[i]<min):
min=list[i]
print(“The minimum among the list of numbers is: “,min)
PART B
1. Mention the different types of iterative structure allowed in Python. Explain the use of continue and
break statements with an example.(16) (April/May-19).
Iterations:
For loop
While loop
3
Difference between break and continue:
Break continue
It terminates the current loop and It terminates the current iteration and
executes the remaining statement transfer the control to the next iteration
outside the loop. in the loop.
syntax: syntax:
break continue
for i in "welcome": for i in “welcome":
if(i=="c"): if(i=="c"):
break continue
print(i) print(i)
w w
e e
l l
o
m
e
2. What is an algorithm? Summarize the characteristics of a good algorithm.(8)(April/May-19)
Algorithm Definition:
It is defined as a sequence of instructions that describe a method for solving a problem. In
other words it is a step by step procedure for solving a problem.
The following are the primary factors that are often used to judge the quality of the algorithms.
Time – To execute a program, the computer system takes some amount of time. The lesser is the time
required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space. The lesser is the
memory required, the better is the algorithm.
4
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given problem, some of these
may provide more accurate results than others, and such algorithms may be suitable.
Odd number means the number which is not divided by 2, so the n natural
numbers are considered and they checked whether it is divided by 2 or not then
the non divisible number is printed.
Step 1: Start
Step 2: Read n
Step 3: Repeat Step 4 until i<n
Step 4: Check if (i%2!=0) then print i and i=i+1
Step 5: Stop
2.CONTROL FLOW:
The process of executing the individual statements in a given order is called control flow.
The control can be executed in three ways
a. sequence
b. selection
c. iteration
a. Sequence:
All the instructions are executed one after another is called sequence execution.
5
Example:
Add two numbers:
Step 1: Start
Step 2: get a,b
Step 3: calculate c=a+b
Step 4: Display c
Step 5: Stop
b. Selection:
A selection statement causes the program control to be transferred to a specific part of the program
based upon the condition.
If the conditional test is true, one part of the program will be executed, otherwise it will execute the
other part of the program.
Example
Write an algorithm to check whether he is eligible to vote?
Step 1: Start
Step 2: Get age
Step 3: if age >= 18 print “Eligible to vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop
c. Iteration:
In some programs, certain set of statements are executed again and again based upon conditional test.
i.e. executed more than one time. This type of execution is called looping or iteration.
Example
Write an algorithm to print all natural numbers up to n
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop
6
3.FUNCTIONS:
Function is a sub program which consists of block of code(set of instructions) that performs a
particular task. For complex problems, the problem is been divided into smaller and simpler tasks during
algorithm design
Benefits of Using Functions
Reduction in line of code
code reuse
Better readability
Information hiding
Easy to debug and test
Improved maintainability
5. Identify the simple strategies for developing an algorithm.(8)(Dec/Jan’19) / Write a Python program
to find the factorial of a given number without recursion and with recursion.(8)(Jan’18)
1. iterations
2. Recursions
1. Iterations:
For loop
While loop
7
2. Recursions:
A function that calls itself is known as recursion. Recursion is a process by which a function calls
itself repeatedly until some specified condition has been satisfied.
8
Pseudo code for factorial using recursion:
Main function:
BEGIN GET n
CALL factorial(n)
PRINT fact
IF(n==1) THEN
fact=1 RETURN fact
ELSE
RETURN fact=n*factorial(n-1)
Step 1: Start
Step 2: get a list a
Step 3: for each element (i) in a goto step4 else goto step 8
Step 4: get the index of i assign it to j and goto step 5
Step 5: while (j>0) got to step6 else goto step3
Step 6: if(a[j-1]>a[j]) then swap a[j],a[j-1] and goto step7 else goto step7
Step 7: decrement j value and goto step 5
Step 8: Print the list a
Step 9: Stop
7. Draw a flowchart to accept three distinct numbers, find the greatest and print the result.(8)(Jan’18)
9
8. Draw a flowchart to find the sum of the series 1+2+3+4+5+…..+100. (8)(Jan’18)
9. Outline the Towers of Hanoi problem. Suggest a solution to the Towers of Hanoi problem with
relevant diagrams.(16)(Jan’18) / Write a recursive algorithm, to solve towers of Hanoi
problem.(8)(Dec/Jan’19)
No of efficient moves = 2n – 1
10
Algorithm for tower of hanoii:
Step 1 − Move n-1 disks from source to aux
Step 2 − Move nth disk from source to dest
Step 3 − Move n-1 disks from aux to dest
11
UNIT - 2
PART A
A scalar is a type that can have a single value such as 5, 3.14, or ‘Bob’.
3. What is tuple? How literals of type tuples are written? Give example.(Jan ’18)
Tuple
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists.
The differences between tuples and lists are, the tuples cannot be changed unlike lists
Tuples use parentheses,.()
Creating a tuple is as simple as putting different comma-separated values
Example
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing −
tup1 = ();
Tuple literals
Literals can be defined as a data that is given in a variable or constant.
12
4. Outline the logic to swap the contents of two identifiers without using the third variable. (April/May-
19)
Logic to swap the contents of two identifiers without using the third variable.
In Python, there is a simple construct to swap variables. The following code does the same as above
but without the use of any temporary variable.
x=5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)
Output:
x=10
y=5
PART B
1. Sketch the structures of interpreter and compiler. Detail the differences between them. Explain how
Python works in interactive mode and script mode with examples. (2+2+4) (Dec/Jan’19)
Interpreter Compiler
Translates program one statement at a Scans the entire program and translates
time. it as a whole into machine code.
It takes less amount of time to analyze It takes large amount of time to analyze
the source code but the overall the source code but the overall
execution time is slower. execution time is comparatively faster.
Continues translating the program until It generates the error message only after
the first error is met, in which case it scanning the whole program. Hence
stops. Hence debugging is easy. debugging is comparatively hard.
13
Interactive mode Script mode
A way of using the Python interpreter A way of using the Python interpreter
by typing commands and expressions at to read and execute statements in a
the prompt. script.
Can’t save and edit the code Can save and edit the code
We can see the results immediately. We can’t see the code immediately.
Advantages: Advantages:
1. Python, in interactive mode, is good 1. It is easy to run large pieces of code.
enough to learn, experiment or 2. Editing your script is easier in script
explore. mode.
2. Working in interactive mode is 3. Good for both beginners and
convenient for beginners and for experts
testing small pieces of code
3. Describe about the concept of precedence and associativity of operators with example.(16)(April/May-19)
/ Outline the operator precedence of arithmetic operators in Python.(6)(Jan’18) / Summarize the
precedence of mathematical operators in Python.(8)(Dec/Jan’19)
OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description
14
>><< Right and left bitwise shift
e = (a + b) * c / d #( 30 * 15 ) / 5
print(e)
e = a + (b * c) / d; # 20 + (150/5)
print(e)
When you execute the above program, it produces the following result
90
90
90
50
15
4. Mention the list of keywords available in Python. Compare it with variable name.(8)(April/May-19)
KEYWORDS:
Keywords are the reserved words in Python.
We cannot use a keyword as variable name, function name or any
other identifier.
They are used to define the syntax and structure of the Python language.
Keywords are case sensitive.
A variable allows us to store a value by assigning it to a name, which can be used later.
Named memory locations to store values.
Programmers generally choose names for their variables that are meaningful.
It can be of any length. No space is allowed.
We don't need to declare a variable before using it. In Python, we simply assign a value to
a variable and it will exist.
Value should be given on the right side of assignment operator(=) and variable on left side.
>>>counter =45
print(counter)
>>> a=b=c=100
Assigning multiple values to multiple variables
Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction, multiplication etc.
16
Operator Description Example
Output:
Enter a value 5
Enter b value 8
a=8
b=5
17
UNIT - 3
PART A
1. Write a python program to accept two numbers, multiply them and print the result. (Jan ’18)
2. Write a Python program to accept two numbers,find the greatest and print the result. (Jan ’18)
Output:
Enter the first number:5
Enter the second number:10
The largest number is: 10
18
In while loop, test expression is checked first.The body of the loop is entered only if
the testexpression evaluates to True.
After one iteration, the test expression is checked again. This process continues until
the testexpression evaluates to False.
In Python, the body of the while loop is determined through indentation.
Body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as True. None and 0 are interpreted as False.
4. State the logical operators available in python language with example. (April/May-19)
Output:
false
true
false
5. Comment with an example on the use of local and global variable with the same identifier name.
(April/May-19)
Global and Local variables
There are two types of variables: global variables and local variables.
A global variable can be reached anywhere in the code, a local only in the scope.
Use of local and global variable with the same identifier name
def f():
s = "I love London!" # Local Variable
print(s)
s = "I love Paris!" #Global Variable Output looks like this:
f() I love London!
print(s) I love Paris!
19
PART B
1. Appraise with an example nested if and elif header in Python.(6) / List the three types of conditional
statements and explain them.(16)(Dec/Jan’19)
CONDITIONALS
1. Conditional if
2. Alternative if…else
3. Chainedif…elif…else
4. Nestedif….else
Conditional if:
conditional (if) is used to test a condition, if the condition is true the statements inside if will
be executed.
syntax:
Flowchart:
Example:
Program to provide discount rs 500, if the purchase amount is greater than 2000.
20
alternative(if-else):
In the alternative the condition must be true or false. In this else statement can be
combined with if statement. The else statement contains the block of code that executes when
the condition is false. If the condition is true statements inside the if get executed otherwise
else
part gets executed. The alternatives are called branches, because they are branches in the flow
of execution.
syntax:
Flowchart:
Examples:
Odd or even number Output
n=eval(input("enter a number")) enter a number 4 even number
if(n%2==0):
print("even number")
else:
print("odd number")
21
Example:
Student mark system
22
Nested conditionals:
One conditional can also be nested within another. Any number of condition can be nested
inside one another. In this, if the condition is true it checks another if condition1. If both the
conditions are true statement1 get executed otherwise statement2 get execute. if the condition is false
statement3 gets executed
Example:
greatest of three numbers output
a=eval(input(“enter the value of a”)) enter the value of a 9 enter the value of a
b=eval(input(“enter the value ofb”)) 1
c=eval(input(“enter the value of c”)) enter the value of a 8 the greatest no is 9
if(a>b):
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
2. Explain with an example while loop, break statement and continue statement in Python.(10)(Jan’18)
23
While loop:
While loop statement in Python is used to repeatedly executes set of statement as long as a given
condition is true.
In while loop, test expression is checked first. The body of the loop is entered only if the
test_expression is True. After one iteration, the test expression is checked again. This
process continues until the test_expression evaluates to False.
The statements inside the while starts with indentation and the first unindented line marks the
end.
Syntax
24
Break continue
It terminates the current loop and It terminates the current iteration and
executes the remaining statement transfer the control to the next iteration
outside the loop. in the loop.
syntax: syntax:
break continue
for i in "welcome": for i in “welcome":
if(i=="c"): if(i=="c"):
break continue
print(i) print(i)
w w
e e
l l
Syntax:
Default start value is 0
Default stop value is n-1
Listname[start:stop]
Listname[start:stop:steps]
slices example description
>>> a=[9,8,7,6,5,4]
>>> a[0:3] Printing a part of a list from 0 to 2.
a[0:3] [9, 8, 7]
>>> a[:4] Default start value is 0. so
a[:4] [9, 8, 7, 6] prints from 0 to 3
>>> a[1:] default stop value will be
a[1:] [8, 7, 6, 5, 4] n-1. so prints from 1 to 5
>>> a[:] Prints the entire list.
a[:] [9, 8, 7, 6, 5, 4]
>>> a[2:2] print an empty slice
a[2:2] []
25
>>> a[0:6:2] Slicing list values with step
a[0:6:2] [9, 7, 5] size 2.
>>> a[::-1] Returns reverse of given list
a[::-1] [4, 5, 6, 7, 8, 9] values
def search(list,n):
for i in range(len(list)):
if list[i] == n:
return True
return False
# Driver Code
n = 'Geeks'
if search(list, n):
print("Found")
else:
print("Not Found")
Function is a sub program which consists of set of instructions used to perform a specific task.
A large program is divided into basic building blocks called function.
Syntax:
26
def fun_name(Parameter1,Parameter2…Parameter n): statement1
statement2…
statement n return[expression]
Once we have defined a function, we can call it from another function, program or even
the Pythonprompt.
To call a function we simply type the function name with appropriate arguments.
Example:
x=5 y=4
my_add(x,y)
The order in which statements are executed is called the flow ofexecution
Execution always begins at the first statement of theprogram.
Statements are executed one at a time, in order, from top tobottom.
Function definitions do not alter the flow of execution of the program, but remember that
statements inside the function are not executed until the function is called.
Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the statements
there, and then comes back to pick up where it leftoff.
Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of execution.
This means that you will read the def statements as you are scanning from top to bottom, but you should
skip the statements of the function definition until you reach a point where that function is called.
27
6. Why are functions needed?(6)(April/May-19)
Function is a sub program which consists of set of instructions used to perform a specific task.
A large program is divided into basic building blocks called function.
7. Explain the syntax and structure of user defined functions in Python with examples. Also discuss
about parameter passing in functions.(12)(Dec/Jan’19)
Types of function:
Functions can be classified into two categories:
User defined function
Built in function
i) Built in functions
Built in functions are the functions that are already created and stored in python.
These built in functions are always available for usage and accessed by a programmer. It cannot
be modified.
>>>max(3,4) 4 # returns largest element
28
print(c) add()#Function Call
Strings:
String is defined as sequence of characters represented in quotation marks (either single
quotes ( ‘ ) or double quotes ( “).
An individual character in a string is accessed using aindex.
The index should always be an integer (positive ornegative).
A index starts from 0 ton-1.
Python will get the input at run time by default as astring.
Python does not support character data type. A string of size 1 can be treated as characters.
1. singlequotes(' ')
2. double quotes ("")
3. triple quotes(“””“”””)
Strings are immutablei.e. the contents of the string cannot be changed after it is created.
Immutability:
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.
29
delete a string a=”PYTHON” NameError: name 'my_string'
del a is not defined
9. Write a Python code to perform binary search. Trace it with an example of your
choice.(8)(Dec/Jan’19)
30
31
10) What is a numeric literal? Give examples.(4)(Jan’18)
Numeric literals:
Numeric Literals are immutable.
Numeric literals can belong to following four different numerical types.
Int(signed integers)
Numbers( can be both positive and negative) with no fractional part.
Example: 100
Long(long integers)
Integers of unlimited size followed by lowercase or uppercase L
Example: 87032845L
float(floating point)
Real numbers with both integer and fractional part
Example -26.2
Complex(complex)
In the form of a+bj where a forms the real part and b forms the imaginary part of complex
number.
Example : 3.14j
11.Write a Python program using function to find the sum of first ‘n’ even numbers and print the
result.(6)(Jan’18)
Input : n = 20
Output : 420
Python program using function to find the sum of first ‘n’ even numbers and print the
result.
n=int(input("Enter n value:"))
sum=0
for i in range(2,n+1,2):
sum+=i
print(sum)
Input:5
Output:
6(2+4)
32
12. Write a Python program to generate first ‘N’ Fibonacci numbers. Note: The Fibonacci numbers are
0,1,1,2,3,5,8,13,21,34 where each number is the sum of the preceding two.(8)(Jan’18)
Fibonacci numbers
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....
The first two terms are 0 and 1.
All other terms are obtained by adding the preceding two terms.
This means to say the nth term is the sum of (n-1)th and (n-2)th term.
Python program to generate first ‘N’ Fibonacci numbers
a=0
b=1
n=eval(input("Enter the number of terms: "))
print("Fibonacci Series: ")
print(a,b)
for i in range(1,n,1):
c=a+b
print(c)
a=b
b=c
Output
Enter the number of terms: 6 Fibonacci Series:
01
1
2
3
5
8
33
UNIT - 4
PART A
List Definition:
A list is a collection which is ordered and changeable. In Python lists are written with square
brackets.
Example
#Create a List:
list = ["apple", "banana", "cherry"]
print(list)
2. How to create a list in Python? Illustrate the use of negative indexing . (April/May 2019)
Creation of list:
A list is created by placing all the items (elements) inside a square bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float, string etc.).
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
34
The difference between end and start is the number of elements selected (if step is
1, the default).The start and end may be a negative number. For negative
numbers, the count starts from the end of the array instead of the beginning.
We can access a range of items in a list by using the slicing operator (colon).
my_list = ['p','r','o','g','r','a','m','i','z']
Mutable means, we can change the content without changing the identity. Mutability is the
ability for certain types of data to be changed without entirely recreating it.
Using mutable data types can allow programs to operate quickly and efficiently.
Example for mutable data types are: List, Set and Dictionary
Example :>>>numbers=[42,123]
>>>numbers[1]=5
>>>numbers [42,5]
Here, the second element which was 123 is now turned to be 5.
5. Demonstrate with simple code to draw the histogram in Python. (April/May 2019)
A histogram is a great tool for quickly assessing a probability distribution that is intuitively
understood by almost any audience.
Python offers a handful of different options for building and plotting histograms.
Code to draw the histogram in Python
def histogram(a):
for i in a: Output
sum = ''
****
while(i>0):
*****
sum=sum+'#'
*******
i=i-1
********
print(sum)
************
a=[4,5,7,8,12]
histogram(a)
35
6. What is a module? Give example. (Dec./Jan.’19) / Write a note on modular design. (Jan.’18)
>>>import example
>>>example.add(4,5.5)
9.5
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 function print(), 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.
PART B
Syntax:
for i in sequence:
Syntax:
while (condition):
body of while
Example:
a=[1,2,3,4,5]
i=0 sum=0
while i<len(a):
37
sum=sum+a[i]
i=i+1
print(sum)
Output:
15
1. + (Concatenation)
2. * (Repeatition)
3. Slicing
Concatenation
Adding and printing the items of two lists.
>>> a=[2,3,4,5,6,7,8,9,10]
>>>b=[20,30]
>>> print(a+b)
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
Repetition
Create a multiple copies of the same list.
>>> print(b*3)
[20, 30, 20, 30, 20, 30]
List slicing:
List slicing is an operation that extracts a subset of elements from an list and
packages them as another list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]
default start value is 0
default stop value is n-1
38
3. Compare and contrast tuples and lists in Python.(4) (Dec./Jan.’19)
List Tuples
List are enclosed in brackets[ ] and their Tuples are enclosed in parenthesis ( )
elements and size can be changed and cannot be updated
Homogenous Heterogeneous
Example: Example:
List = [10, 12, 15] Words = ("spam", "egss")
Or Words = "spam",
"eggs"
Access: Access:
print(list[0]) print(words[0])
Can contain duplicate elements Can contain duplicate elements.
Faster compared to lists
Slicing can be done Slicing can be done
Usage: Usage:
List is used if a collection of data that Tuple can be used when data
Does’nt need random access. cannot be changed.
List is used when data can be modified A tuple is used in combination
frequently with a dictionary i.e. a tuple might
represent a key.
4. Write a Python program to store ‘n’ numbers in a list and sort the list using selection sort. (8) (Jan.’18)
a=[]
OUTPUT:
Enter how many numbers 5
Enter the numbers one by one
5
6
2
1
3
Before sorting
['5', '6', '2', '1', '3']
After sorting
['1', '2', '3', '5', '6']
5. Demonstrate with the code the various operations that can be performed on tuples. (April/May 2019)
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
40
>>>print(a[0]) Accessing the item in
Indexing 20 the position 0
>>> a[2] Accessing the item in
60 the position 2
Slicing >>>print(a[1:3]) Displaying items
(40,60) from1st till 2nd.
Concatenation >>> b=(2,4) Adding tuple
>>>print(a+b) elements at the end
>>>(20,40,60,”apple”,”ball”,2,4) of another tuple
elements
Repetition >>>print(b*2) repeating the tuple in
>>>(2,4,2,4) n no of times
>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a True
Membership Returns True if
>>> 100 in a
element is present in
False
tuple. Otherwise
>>> 2 not in a
returns false.
False
>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4) Returns True if all
Comparison
>>> a==b elements in both
False elements are same.
>>> a!=b Otherwise returns
True false
Operations on dictionary:
1. Accessing anelement
2. Update
41
3. Add element
4. Membership
Example:
>>> a={1:"one",2:"two"}
>>> print(a)
{1: 'one', 2: 'two'}
Operations on dictionary:
1. Accessing anelement
2. Update
3. Add element
4. Membership
42
8. Write a Python program to perform linear search on a list.(8) (Jan.’18)
l=[]
n=eval(input("Enter how many elements "))
print("Enter the elements one by one ")
for i in range(n):
l.append(eval(input()))
s=eval(input("Enter an element to search "))
flag=0
for i in range(n):
if (l[i]==s):
flag=1
break
if (flag==1):
print(s," is found at ",i+1,”position”)
else:
print(s," not found ")
OUTPUT:
Enter how many elements 5
Enter the elements one by one
3
2
4
5
1
Enter an element to search 1
1 is found at 5 position
OUTPUT:
43
Enter how many numbers 5
Enter the numbers one by one
5
6
2
1
3
Before sorting
['5', '6', '2', '1', '3']
After sorting
['1', '2', '3', '5', '6']
10. Outline the algorithm and write a Python program to sort the numbers in ascending order using
merge sort(16) (April/May 2019)
l1=[]
l2=[]
l3=[]
n1=eval(input("Enter the size of first list "))
n2=eval(input("Enter the size of second list "))
print("Enter the First List elements ")
for i in range(n1):
l1.append(eval(input()))
print("Enter the Second List elements ")
for i in range(n2):
l2.append(eval(input()))
l1.sort()
l2.sort()
i=0
j=0
k=0
while (i<n1 and j<n2):
if (l1[i]>l2[j]):
l3.append(l2[j])
j=j+1
else:
l3.append(l1[i])
i=i+1
if (i<n1):
for m in range(i,n1):
l3.append(l1[m])
44
else:
for m in range(j,n2):
l3.append(l2[m])
print("First List elements are ",l1)
print("Second List elements are ",l2)
print("Resultant List elements are ",l3)
OUTPUT:
45
UNIT - 5
PART A
1. Write a Python script to display the current date and time. (Jan.’18)
import datetime
now = datetime.datetime.now()
print("Current date and time: ")
print(str(now))
Output:
2017-12-29 11:24:48.042720
2. Categorize the different types of errors arises during programming .interpret the following python
code. (April/May 2019)
>>>import os
>>>print cwd
/home/dinsale
Files are organized into directories(also called “folders”). Every running program has
a “current directory”, which is the default directory for most operations.
The OS modules provides functions for working with files and directories.(“os” stands
for operating system.
os.getcwd() returns the name of the current working directory.
The result in this example is /home/dinsale which is the home directory of the user
named dinsale
46
PART B
1. Explain about the file reading and writing operations using format operator with Python code.(16)
(April/May 2019) / Discuss about the use of format operator in file processing.(8) Dec./Jan.’19
Format operator
The argument of write( ) has to be a string, so if we want to put other values along with
the string in a file, we have to convert them to strings.
47
2. Tabulate the different modes for opening a file and explain the same.(16) (Jan.’18)
Modes in file:
modes description
r read only mode
w write only
a appending mode
r+ read and write mode
w+ write and read mode
Python allows you to read, write and delete files
Use the function open("filename","w+") to create a file. The + tells the python interpreter to open
file with read and write permissions.
To append data to an existing file use the command open("Filename", "a")
Use the read function to read the ENTIRE contents of a file
Use the readlines function to read the content of the file one by one.
f = open(“workfile”,”w”)
print f
file = open(“testfile.txt”,”w”)
file.write(“Hello World”)
file.write(“This is our new text file”)
file.write(“and this is another line.”)
file.write(“Why? Because we can.”)
file.close()
$ cat testfile.txt
Hello World
This is our new text file
and this is another line.
Why? Because we can.
file = open(“testfile.txt”, “r”)
for line in file:
print line,
Output:
Hello World
This is our new text file
and this is another line. Why? Because we can.
48
3. Explain the commands used to read and write into a file with examples. (8) Dec./Jan.’19)
Operations on Files:
In Python, a file operation takes place in the following order,
1. Opening a file
2. Reading / Writing file
Modes in file:
modes description
r read only mode
w write only
a appending mode
r+ read and write mode
w+ write and read mode
49
4. Explain about how exceptions are handled with example.(8) (April/May 2019) / Describe how
exceptions are handled in Python with necessary example.(16) Dec./Jan.’19 /Appraise the use of try
block and except block in Python with syntax.(6) (Jan.’18)
Exception Handling:
Exception handling is done by try and catch block.
Suspicious code that may raise an exception, this kind of code will be placed in try block.
A block of code which handles the problem is placed in except block.
Catching Exceptions:
1. try…except
2. try…except…inbuilt exception
3. try… except…else
try…except:
Syntax:
try:
code that create exception
except:
exception handling statement
50
Example: Output
try: enter age:8
age=int(input("enter age:")) ur age is: 8
print("ur age is:",age) enter age: f
except: enter a valid age
print("enter a valid age")
try…except…inbuilt exception:
Syntax
try:
code that create exception except inbuilt
exception:
Example: Output
try: enter
age=int(input("enterage:")) age:d
print("ur age is:",age) enter a
except ValueError: valid age
print("enter a valid
age")
Else part will be executed only if the try block doesn’t raise an exception.
Python will try to process all the statements inside try block. If value error occurs, the flow of
control will immediately pass to the except block and remaining statement in try block will
be skipped.
Syntax
try:
code that create exception except:
exception handlin
statement else:
statements
Example program Output
51
try: enter your age: six
age=int(input("enter your entered value is not a
age:")) number enter your age:6
except ValueError: your age is 6
print("entered value is not a
number")
else:
print("your age :”,age)
try:
b = float(56+78/0)
except Exception, Argument:
print 'This is the Argument\n', Argument
The output obtained is as follows
This variable receives the value of the exception mostly containing the cause of the
exception. The variable can receive a single value or multiple values in the form of a tuple. This
tuple usually contains the error string, the error number, and an error location.
6. Design a Python code to count the number of words in Python file.(8) (April/May 2019)
Note: Initially create a file with name “wordcount.txt” and enter the required text (Eg. Hai I am a
test program) and save in the python file path.
PROGRAM:
num_words = 0
f=open("wordcount.txt", 'r')
line=f.read()
words=[]
words=line.split()
print(words)
print("Number of words:")
print(len(words))
OUTPUT:
Number of words: 6
52