You are on page 1of 17

PWP question paper answer sheet

Programming With Python -I (USCS102)

1 0
Q1. Attempt any FIVE of the following. (10 Marks)
a) Name different modes of Python
Ans: Interactive Mode : Interactive mode is a command line shell. If we write a python
program in the command line shell. Typically the interactive mode is used to test the features
of the python, or to run a smaller script that may not be reusable.
Batch Mode : Batch mode is mainly used to develop business applications. In batch mode,
we can write a group of python statements in any one of the following editors or IDEs
Editors : Notepad, Notepad++, editPlus, nano, gedit, IDLE, Etc..
IDEs : pycharm, Eric, Eclipse, Netbeans, Etc..

b) List identity operators


Ans: Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Operator Description Example
is Returns true if both variables are the same object x is y
is not Returns true if both variables are not the same object x is not y

c) Describe Dictionary
Ans: In Python, a Dictionary can be created by placing a sequence of elements within curly
{} braces, separated by ‘comma’. Dictionary holds pairs of values, one being the Key and the
other corresponding pair element being its Key:value. Values in a dictionary can be of any
data type and can be duplicated, whereas keys can’t be repeated and must be immutable.
Dictionary keys are case sensitive, the same name but different cases of Key will be treated
distinctly.
# Creating a Dictionary
Dict = {1: 'PWP', 2: 'MAD', 3: 'NIS'}
print("This is subject")
print(Dict)
d) State use of namespace in Python
Ans: A namespace is a collection of currently defined symbolic names along with
information about the object that each name references. You can think of a namespace as a
dictionary in which the keys are the object names and the values are the objects themselves.
Each key-value pair maps a name to its corresponding object.

e) List different Object Oriented features supported by Python.


1

1 0
Ans: 1. Easy to code: Python is a high-level programming language. Python is very easy to
learn the language as compared to other languages like C, C#, Javascript, Java, etc
2. Free and Open Source: Python language is freely available at the official website.Since it
is open-source, this means that source code is also available to the public. So you can
download it as, use it as well as share it.
3. Object-Oriented Language: One of the key features of python is Object-Oriented
programming. Python supports object-oriented language and concepts of classes, objects
encapsulation, etc.
4. High-Level Language: Python is a high-level language. When we write programs in
python, we do not need to remember the system architecture, nor do we need to manage the
memory.

f) Write steps involved in creation of a user defined exception?


Ans: Step 1: Create User Defined Exception Class
Step 2: Raising Exception
Step 3: Catching Exception
Step 4: Write a Program for User-Defined Exception in Python
class YourException(Exception):
def __init__(self, message):
self.message = message
try:
raise YourException("Something is fishy")
except YourException as err:
# perform any action on YourException instance
print("Message:", err.message)

g) Describe Python Interpreter


Ans: Python executes the code line by line i.e., Python is an interpreter language. As we
know the computer can’t understand our language, it can only understand the machine
language i.e., binary language. So, the Python interpreter converts the code written in python
language by the user to the language which computer hardware or system can understand. It
does all the time whenever you run your python script.

Q.2) Attempt any THREE of the following. (12 Marks)

1 0
a) Explain two Membership and two logical operators in python with appropriate
examples
Membership operators
 Ans: Operator : in
Description: Evaluates to true if it finds a variable in the specified sequence and false
otherwise.
Example: x in y, here in results in a 1 if x is a member of sequence y.
 Operator : not in
Description: Evaluates to true if it does not finds a variable in the specified sequence
and false otherwise.
Example: x not in y, here not in results in a 1 if x is not a member of sequence y.
logical operators
 Operator: and Logical AND
Description: If both the operands are true then condition becomes true. (a and b) is
true.
Example: (a and b) is true.
 Operator: or Logical OR
Description: If any of the two operands are non-zero then condition becomes true.
Example: (a or b) is true.
 Operator: not Logical NOT
Description : Used to reverse the logical state of its operand.
Example: Not(a and b) is false.

b) Describe any four methods of lists in Python


Ans: 1) append() - Adds an element at the end of the list
EX- List = ['Mathematics', 'chemistry', 1997, 2000]
List.append(20544)
print(List)
2) remove() - Element to be deleted is mentioned using list name and element.
EX- List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
List.remove(3)

1 0
print(List)
3) count() - Returns the number of elements with the specified value
EX- List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))
4) insert() - Inserts an elements at specified position
EX - List = ['Mathematics', 'chemistry', 1997, 2000]
# Insert at index 2 value 10087
List.insert(2,10087)
print(List)

c) Comparing between local and global variable


Ans:
Global Variable Local Variable

Global Variable Local Variables are declared within a function


are declared outside all the function blocks. block.

The scope remains throughout the program. The scope is limited and remains within the
function only in which they are declared.

Global variables are stored in the data Local variables are stored in a stack in
segment of memory. memory.

We cannot declare many variables with the We can declare various variables with the
same name. same name but in other functions.

d) Write a python program to print Fibonacci series up to n terms


Ans: # Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:

1 0
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

Q.3) Attempt any THREE of the following. (12 Marks)


a) Write a program to input any two tuples and interchange the tuple variable.
Ans: t1=eval(input("Enter Tuple 1"))
t2=eval(input("Enter Tuple 2"))
print ("Before SWAPPING")
print ("First Tuple",t1)
print ("Second Tuple",t2)
t1,t2=t2,t1
print ("AFTER SWAPPING")
print ("First Tuple",t1)
print ("Second Tuple",t2)
Output:
Enter Tuple 1(1,2,3)
Enter Tuple 2(5,6,7,8)

1 0
Before SWAPPING
First Tuple (1, 2, 3)
Second Tuple (5, 6, 7, 8)
AFTER SWAPPING
First Tuple (5, 6, 7, 8)
Second Tuple (1, 2, 3)

b) Explain different loops available in python with suitable examples.


Ans: 1) While Loop: In python, while loop is used to execute a block of statements
repeatedly until a given condition is satisfied. And when the condition becomes false, the line
immediately after the loop in the program is executed.
Syntax : while expression:
statement(s)
Example:
count = 0
while (count < 3):
count = count + 1
print("Python")
2) for Loop: For loops are used for sequential traversal. For example: traversing a list or
string or array etc. In Python, there is no C style for loop
Syntax:
for iterator_var in sequence:
statements(s)
Example:
# Iterating over range 0 to n-1
n=4
for i in range(0, n):
print(i)
3) Nested Loops: Python programming language allows to use one loop inside another loop.
Following section shows few examples to illustrate the concept.
Syntax: for iterator_var in sequence:
for iterator_var in sequence:

1 0
statements(s)
statements(s)
Example:
# nested for loops in Python
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()

c) Describe various modes of file object? Explain any two in detail.


Ans: A file object allows us to use, access and manipulate all the user accessible files. One
can read and write any such files.
r: Opens a file for reading only
r+: Opens a file for both reading and writing
w: Opens a file for writing only
w+: Open a file for writing and reading.
a: Opens a file for appending
a+: Opens a file for both appending and reading
x: This mode will write the file only when the file will not exist as it will create the one and
write in it.
x+: This mode will read and write the file in the same condition as the x mode.
 open(): Opens a file in given access mode.
open(file_address, access_mode)
Examples of accessing a file: A file can be opened with a built-in function called open(). This
function takes in the file’s address and the access_mode and returns a file object.
 read([size]): It reads the entire file and returns it contents in the form of a string.
Reads at most size bytes from the file (less if the read hits EOF before obtaining size
bytes). If the size argument is negative or omitted, read all data until EOF is reached.

# Reading a file
f = open(__file__, 'r')

1 0
#read()
text = f.read(10)
print(text)
f.close()

 write(string): It writes the contents of string to the file. It has no return value. Due to
buffering, the string may not actually show up in the file until the flush() or close()
method is called.
# Writing a file
f = open(__file__, 'w')
line = 'Welcome Geeks\n'
#write()
f.write(line)
f.close()

d) Illustrate the use of method overriding? Explain with example


Ans: Method overriding is an ability of any object-oriented programming language that
allows a subclass or child class to provide a specific implementation of a method that is
already provided by one of its super-classes or parent classes. When a method in a subclass
has the same name, same parameters or signature and same return type(or sub-type) as a
method in its super-class, then the method in the subclass is said to override the method in the
super-class.
# method overriding
# Defining parent class
class Parent():
# Constructor
def __init__(self):
self.value = "Inside Parent"
# Parent's show method
def show(self):
print(self.value)
# Defining child class
class Child(Parent):

1 0
# Constructor
def __init__(self):
self.value = "Inside Child"
# Child's show method
def show(self):
print(self.value)
# Driver's code
obj1 = Parent()
obj2 = Child()
obj1.show()
obj2.show()
Output:
Inside Parent
Inside Child

Q.4) Attempt any THREE of the following. (12 Marks)


a) Use of any four methods of tuple in python?
Ans: Python has two built-in methods that you can use on tuples.
1. count() - Returns the number of times a specified value occurs in a tuple
Syntax:
tuple.count(value)
Parameter Values:
Value - Required The item to search for
Example :
# Return the number of times the value 5 appears in the tuple:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.count(5)
print(x)
2. index() - Searches the tuple for a specified value and returns the position of where it
was found.
Syntax:

1 0
tuple.index(value)
Parameter Values:
Value - Required The item to search for
Example:
# Search for the first occurrence of the value 8, and return its position:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.index(8)
print(x)

b) Write a python program to read contents of first.txt file and write same content in
second.txt file
Ans: first.txt file:
This is python language.
with open('first.txt', 'r') as firstfile, \
open('second.txt', 'w') as secondfile:
print("content saved successfully")
for content in firstfile:
secondfile.write(content)
Output:
content saved successfully
This is python language.
c) Show how try…except blocks is used for exception handling in Python with example.
Ans: try-expect statement - If the Python program contains suspicious code that may throw
the exception, we must place that code in the try block. The try block must be followed with
the except statement, which contains a block of code that will be executed if there is some
exception in the try block.
Syntax :
try:
#block of code
except Exception1:
#block of code
except Exception2:

10

1 0
#block of code
#other code
Example :
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")
d) Write the output for the following if the variable fruit=’banana’:
>>>fruit[:3]
>>>fruit[3:]
>>>fruit[3:3]
>>>fruit[:]
Ans: fruit = ‘banana’
print("Original item is - ", fruit)
f1 = fruit[:3]
print("Element in range :3 is - ", f1)
f2 = fruit[3:]
print("Element in range 3: is - ", f2)
f3 = fruit[3:3]
print("Element in range 3:3 is -", f3)
f4 = fruit[:]
print("Element in range : is -", f4)
Output:
Original item is - banana
Element in range :3 is - ban
Element in range 3: is - ana
Element in range 3:3 is –
Element in range : is – banana

11

1 0
Q.5) Attempt any TWO of the following. (12 Marks)
a) Determine various data types available in Python with example.
Ans: Python has five built in primary data types:
i) Numbers
ii) string
iii) List
iv) tuple
v) Dictionary
i) Numbers -The number data types are to store numeric values. python have four different
types in numbers.
 int (signed integers) : The int is the most prefered & commonly used data types. it
stores signed numeric value without decimal point.
Ex - a = 450 , b = 66, c = -87
x = 99
print(x)
 long (long integer) : The long store signed long integer. Internally, they can also
represent octal of Hexa decimal value. Python allow uppercase L with long.
Ex – a = 543545L, b = 5685L
 Float : Float stores the signed floating point real value or decimal Point.
Ex – a = 45.11, b = 78.33, c = 44.0
X = 36.3
Print (x)
 Complex : complex number consists of an ordered pair of real Floating point. number
denoted by x+yj where x & y are the number and j is the imaginary unit.
Ex – a = 8.20j, b = 72.2j
X = 91.02j
Print(x)
ii) String - string is set of contiguous set of characters represented in single of double quotes.
Ex - str1 =” This is string"
print (str1)
iii) List - List are represented in square braces []. list is similar to array But it is not array is
static, where list is dynamic in size. list has no datatype bounding.

12

1 0
Ex - list1 = [ 20, 10, 5, 9, " Rohan", 88.01]
Print (list1)
iv) Tuple - Tuple store sequence of value / object Tuple is set of value separated by comma
(,) enclosed in parenthesis () Tuple does not allow updation in size of element. Tuple is
readonly entity.
Ex – tup1 = ( 80, 21, 11.22, “Sagar”, ‘Rohan’)
Print(tup1)
v) Dictionary - dictionary is represented in pair of curly braces {}. & its syntax is {key :
value}. the data type of index (key ) & element (value)
Ex - dict1 = { "Rohan : ""12/01/2002", “ sagar:” "24 /05/1996"}
Print (dict1)

b) Write a python program to calculate factorial of given number using function.


Ans: # factorial of given number
import math
def factorial(n):
return(math.factorial(n))
# Driver Code
num = 5
print("Factorial of", num, "is", factorial(num))
Output :
Factorial of 5 is 120
c) Show the output for the following:
1. >>> a=[1,2,3]
>>>b=[4,5,6]
>>> c=a+b
2. >>>[1,2,3]*3
3. >>>t=[‘a’,’b’,’c’,’d’,’e’,’f’]
>>>t[1:3]=[‘x’,’y’]
>>>print t
Ans:

13

1 0
Output :
1. [1, 2, 3, 4, 5, 6]
2. [1, 2, 3, 1, 2, 3, 1, 2, 3]
3. ['a', 'x', 'y', 'd', 'e', 'f']

Q.6) Attempt any TWO of the following. (12 Marks)


a) Describe Set in python with suitable examples.
Ans: A Set is an unordered collection data type that is iterable, mutable and has no duplicate
elements.Since sets are unordered, we cannot access items using indexes like we do in lists.
myset = set(["a", "b", "c"])
print(myset)
# Adding element to the set
myset.add("d")
print(myset)
Output:
{'c', 'b', 'a'}
{'d', 'c', 'b', 'a'}
 Set Union
Union of two sets is a set of all elements from both sets. Union is performed using pipe
operator (|) operator so you can be accomplished using the function union().
Example
A={1, 2, 3, 4, 5)
B=(4, 5, 6, 7, 8)
C = A|B #OR C = A.union(B)
print("Set A contains:"A)
print("Set B contains:"B)
print("The UNION operation results:",C)
This will result as:
Set A contains: (1, 2, 3, 4, 5)
Set B contains: {4, 5, 6, 7, 8}
The UNION operation results: {1, 2, 3, 4, 5, 6, 7, 8)

14

1 0
 Set Intersection
Intersection of A and B is a set of elements that are common in both sets. The Intersection is
performed using (&) operator. Same can be accomplished using the function intersection().
A={1, 2, 3, 4, 5)
B=(4, 5, 6, 7, 8)
C= A&B #OR C = A.intersection(B)
print("Set A contains:"A)
print("Set B contains :"B)
print("The INTERSECTION operation results:",C)
This will result as:
Set A contains: {1, 2, 3, 4, 5)
Set B contains: (4, 5, 6, 7, 8)
The INTERSECTION operation results: {4, 5}
 Set Difference
Difference of A and B (A-B) Is a set of elements that are only In A but not in B. Similarly, B-
A is a set of element in B but not in A. The Difference is performed using (-) operator. Same
can be accomplished using the function difference()
Example
A=(1,2,3,4,5)
B=(4,5,6,7,8}
C = A-B #OR A .difference(B)
D = B-A #OR B.difference(A)
print("A-B results as",C)
print("B-A results as :",D)
The output will be:
A-B results as: (1,2,3)
B-A results as: (8,6,7)
 Set Symmetric_Difference
 Symmetric Difference of A and B is a set of elements in both A and B except those
that are common in both. The Symmetric difference is performed using (a) operator.
Same can be accomplished using the function symmetric difference().
Example

15

1 0
A={1,2,3,4,5)
B=(4, 5, 6, 7, 8)
C = A^B #OR A.symmetric difference (B)
print("Symmetric difference results as "C)
This will result as:
Symmetric difference results as : {1, 2, 3, 6, 7, 8)

b) Illustrate class inheritance in Python with an example


Ans: Inheritance allows us to define a class that inherits all the methods and properties from
another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Create a Parent Class :
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
Create a Child Class : To create a class that inherits the functionality from another class,
send the parent class as a parameter when creating the child class:
x = Student("Mike", "Olsen")
x.printname()

c) Design a class Employee with data members: name, department and salary. Create
suitable methods for reading and printing employee information
Ans: class Employee:
__name=""

16

1 0

You might also like