Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Time: 3 Hrs.

……………………………………………………………………………………………………………………
…………………………………

a) Name different modes of Python

Python has two basic modes: script and interactive.

The normal mode is the mode where the scripted and finished . py files are
run in the Python interpreter.

Interactive mode is a command line shell which gives immediate feedback for
each statement, while running previously fed statements in active memory.

b) List identity operators

Operator Description Example


is Returns True if both variables are the same x is y
object

is not Returns True if both variables are not the x is not y


same object

c) Describe Dictionary

A dictionary is a collection which is unordered, changeable and indexed. In


Python dictionaries are written with curly brackets, and they have keys and
values.

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

d) State use of namespace in Python

A namespace is a simple system to control the names in a program.

Python implements namespaces in the form of dictionaries. It maintains a


name-to-object mapping where names act as keys and the objects as values.

e) List different Object Oriented features supported by Python.

Python OOPs Concepts


 Object.
 Class.
 Method.
 Inheritance.
 Polymorphism.
 Data Abstraction.
 Encapsulation.

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

1. Since all exceptions are classes, the programme is supposed to create


his own exception as a class. Also, he should make his class as a
sub class to the in-built
„Exception‟ class.
class MyException(Exception):
def init (self, arg):
self.msg = arg
Here, MyException class is the sub class for „Exception‟ class. This
class has a constructor where a variable „msg‟ is defined. This „msg‟
receives a message passed from outside through „arg‟.

2. The programmer can write his code; maybe it represents a group of


statements or a function. When the programmer suspects the
possibility of exception, he should raise his own exception using „raise‟
statement as:
raise MyException(‘message’)
Here, raise statement is raising MyException class object that contains
the given
„message‟.

3. The programmer can insert the code inside a „try‟ block and catch the
exception using
„except‟ block
as:
try:
code
except MyException as
me: print me

Here, the object „me‟ contains the message given in the raise statement.

g) Describe Python Interpreter


The Python interpreter is a virtual machine, meaning that it is software that
emulates a physical computer.

The Python interpreter is a bytecode interpreter: its input is instruction


sets called bytecode

h) List features of Python

 Easy to code: Python is high level programming language. ...


 Free and Open Source: ...
 Object-Oriented Language: ...
 GUI Programming Support: ...
 High-Level Language: ...
 Extensible feature: ...
 Python is Portable language: ...
 Python is Integrated language:

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

a) Explain two Membership and two logical operators in python with


appropriate examples.

Membership Operators: in and not in operators.

x=4
y=8
list = [1, 2, 3, 4, 5 ];
if ( x in list ):
print("Line 1 - x is available in the given list")
else:
print("Line 1 - x is not available in the given list")
if ( y not in list ):
print("Line 2 - y is not available in the given list")
else:
print("Line 2 - y is available in the given list")
o/p

Line 1 - x is available in the given list


Line 2 - y is not available in the given list

>>>

Logical operators in Python are AND, OR and NOT.

a = True
b = False
print(('a and b is',a and b))
print(('a or b is',a or b))
print(('not a is',not a))
o/p

('a and b is', False)

('a or b is', True)

('not a is', False)

>>>

b) Describe any four methods of lists in Python

append() Method
fruits = ['apple', 'banana', 'cherry']
fruits.append("orange")

clear() Method
fruits = ['apple', 'banana', 'cherry', 'orange']

fruits.clear()

sort() Method
cars = ['Ford', 'BMW', 'Volvo']

cars.sort()
pop() Method
fruits = ['apple', 'banana', 'cherry']

fruits.pop(1)

count() Method
fruits = ['apple', 'banana', 'cherry']

x = fruits.count("cherry")

remove() Method
fruits = ['apple', 'banana', 'cherry']

fruits.remove("banana")

c) o paring between local and global variable


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

Number = int(input("\nPlease Enter the Range Number: "))

i=0

First_Value = 0

Second_Value = 1

while(i < Number):

if(i <= 1):


Next = i

else:

Next = First_Value + Second_Value

First_Value = Second_Value

Second_Value = Next

print(Next)

i=i+1

o/p

Please Enter the Range Number: 7

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

a) Write a program to input any two tuples and interchange the tuple
variable.

t = (1,2,3,4,5)

t1 = (13,23,36,47,75)

t,t1=t1,t

print(t)
print(t1)

o/p

(13, 23, 36, 47, 75)

(1, 2, 3, 4, 5)

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

The for loop in Python is used to iterate the statements or a part of the
program several times. It is frequently used to traverse the data structures
like list, tuple, or dictionary.

for letter in 'Python':


print 'Current Letter :', letter
o/p:

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n

while loop
while expression:
statement(s)

count = 0
while (count < 9):
print 'The count is:', count
count = count + 1

print "Good bye!"


o/p-
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!
While with else:

count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
o/p-
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

nested while loop


for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
or

while expression:
while expression:
statement(s)
statement(s)

i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print i, " is prime"
i=i+1

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

There are four different methods (modes) for opening a file:

 r - Read - Default value. Opens a file for reading, error if the file does
not exist
 a - Append - Opens a file for appending, creates the file if it does not
exist
 w - Write - Opens a file for writing, creates the file if it does not exist
 x - Create - Creates the specified file, returns an error if the file exist

In addition, the file should be handled as binary or text mode:

 t- Text - Default value. Text mode


 b - Binary - Binary mode (e.g. images)

Read a File
The read() method is used to read files.

Before read a file must open it using open() function.

f = open("demofile.txt", "r")
print(f.read())
Read Only Parts of the File
By default the read() method returns the whole text, but you can also
specify how many character you want to return:

f = open("demofile.txt", "r")
print(f.read(12))
Read Lines
You can return one line by using the readline() method:

f = open("test.py", "r")
print(f.readline())
Write File
To write to an existing file, you must add a parameter to
the open() function:

 a - Append - will append to the end of the file


 w - Write - will overwrite any existing content

f = open("demofile.txt", "a")
f.write("Now the file has one more line!")
f.close()

f = open("demofile.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

Create a New File


To create a new file in Python, use the open() method, with one of the
following parameters:

 x - Create - will create a file, returns an error if the file exist


 a - Append - will create a file if the specified file does not exist
 w - Write - will create a file if the specified file does not exist

f = open("demofile.txt", "x")
f.close()

f = open("demofile_1.txt", "a")
f.close()

f = open("demofile_1.txt", "w")
f.close()

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


If a class inherits a method from its superclass, then there is a chance to
override the method provided.

You can always override your parent class methods.

class Parent:
def echo(self):
print('I am from Parent class')

class Child (Parent):


def echo(self):
print('I am from Child class')

p = Parent()
c = Child()

p.echo()
c.echo()

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

a) Use of any four methods of tuple in python?

len()
Returns the number of elements in the tuple.

>>> t1=(12,45,43,8,35)
>>> len(t1)
5

max()
If the tuple contains numbers, the heighest number will be returned.
>>> t2=('python', 'java', 'C++')
>>> max(t2)
'python'

min()
If the tuple contains numbers, the lowest number will be returned.

>>> t1=(12,45,43,8,35)
>>> min(t1)
8

count()
Returns the number of times a specified value occurs in a tuple

>>> t1 = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
>>> x = t1.count(5)
>>> print(x)

index()
Searches the tuple for a specified value and returns the position of where it
was found.

>>> t = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
>>> x = t.index(8)
>>> print(x)

b) Write a python program to read contents of first.txt file and write


same content in second.txt

file.

File 1.py

with open("1.py") as f:
with open("out.txt", "w") as f1:

for line in f:

f1.write(line)

o/p

copy contents to file out.txt

with open("1.py") as f:

with open("out.txt", "w") as f1:

for line in f:

f1.write(line)

c) Show how try…except blocks is used for exception handling in Python


with example

try() is used in Error and Exception Handling


There are two kinds of errors :
 Syntax Error : Also known as Parsing Errors, most basic. Arise when the
Python parser is unable to understand a line of code.
 Exception : Errors which are detected during execution. eg –
ZeroDivisionError.
List of Exception Errors :
 IOError : if file can’t be opened
 KeyboardInterrupt : when an unrequired key is pressed by the user
 ValueError : when built-in function receives a wrong argument
 EOFError : if End-Of-File is hit without reading any data
 ImportError : if it is unable to find the module
Basic Syntax :
try:
// Code
except:
// Code

def divide(x, y):


try:
result = x // y
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")

divide(3, 0)

d) Write the output for the following if the variable fruit=’banana’:

>>>fruit[:3]

>>>fruit[3:]

>>>fruit[3:3]

>>>fruit[:]

ban

ana

banana

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

a) Determine various data types available in Python with example

Numbers
Integers, floating point numbers and complex numbers fall under Python
numbers category.

They are defined as int, float and complex classes in Python.


a=5
a = 2.0
a = 1+2j

List is an ordered sequence of items. It is one of the most used datatype in


Python and is very flexible. All the items in a list do not need to be of the same
type.

a = [1, 2.2, 'python']

Tuple is an ordered sequence of items same as a list. The only difference is


that tuples are immutable. Tuples once created cannot be modified.

t = (5,'program', 1+3j)

String is sequence of Unicode characters. We can use single quotes or double


quotes to represent strings. Multi-line strings can be denoted using triple
quotes, ''' or """.

s = "This is a string"

s = '''A multiline
string'''
Set is an unordered collection of unique items. Set is defined by values
separated by comma inside braces { }. Items in a set are not ordered.
a = {5,2,3,1,4}

Dictionary is an unordered collection of key-value pairs.


It is generally used when we have a huge amount of data. Dictionaries are
optimized for retrieving data. We must know the key to retrieve the value.

In Python, dictionaries are defined within braces {} with each item being a
pair in the form key:value. Key and value can be of any type.
>>> d = {1:'value','key':2}

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


function

def factorial(num):
if num == 1:
return num
else:
return num * factorial(num - 1)
num = int(input("Enter a Number: "))

if num < 0:
print("Factorial cannot be found for negative numbers")
elif num == 0:
print("Factorial of 0 is 1")
else:
print("Factorial of", num, "is: ", factorial(num))
o/p

Enter a Number: 6

Factorial of 6 is: 720

c) Show the output for the following:

1. >>> a=[1,2,3]

>>>b=[4,5,6]

>>> c=a+b

Nothing but if used Print(c) then

[1, 2, 3, 4, 5, 6]

2. >>>[1,2,3]*3
Nothing but if used print([1,2,3]*3) then
print([1,2,3]*3)

3. >>>t=[‘a’,’b’,’c’,’d’,’e’,’f’]

>>>t[1:3]=[‘x’,’y’]

>>>print t

File "main.py", line 1

t=[‘a’,’b’,’c’,’d’,’e’,’f’]

SyntaxError: invalid character in identifier

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

a) Describe Set in python with suitable examples.

 The set in python can be defined as the unordered collection of various


items enclosed within the curly braces.
 The elements of the set can not be duplicate.
 The elements of the python set must be immutable.

Creating a set

The set can be created by enclosing the comma separated items with the curly
braces. Python also provides the set method which can be used to create the
set by the passed sequence.

 using curly braces

Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "S


unday"}
print(Days)

 using set() method


Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
, "Sunday"])
print(Days)

Set operations

Adding items to the set

Months = set(["January","February", "March", "April", "May", "June"])


Months.add("July");
Months.add("August");
print("\nPrinting the modified set...");
print(Months)

o/p: {'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}

Removing items from the set

Python provides discard() method which can be used to remove the items
from the set. also provide the remove() method to remove the items from the
set.

Difference between discard() and remove()

Months = set(["January","February", "March", "April", "May", "June"])

Months.discard("Feb"); #will not give error although the key feb is not availab
le in the set

Months.remove("Jan") #will give an error as the key jan is not available in the
set.

Months.discard("January");
Months.discard("May");

Months.remove("January");
Months.remove("May");
Also use the pop() method to remove the item, this method will always
remove the last item.
Months.pop();
Months.pop();
Python provides the clear() method to remove all the items from the
set.
Months.clear()

Union of two Sets

The union of two sets are calculated by using the or (|) operator. The union of
the two sets contains the all the items that are present in both the sets.

Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1|Days2) #printing the union of the sets

Output:

{'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday', 'Monday', 'Thursday'}

Intersection of two sets

The & (intersection) operator is used to calculate the intersection of the two
sets in python. The intersection of the two sets are given as the set of the
elements that common in both sets.

set1 = {"Ayush","John", "David", "Martin"}


set2 = {"Steve","Milan","David", "Martin"}
print(set1&set2) #prints the intersection of the two sets

Output:

{'Martin', 'David'}

Difference of two sets

The difference of two sets can be calculated by using the subtraction (-)
operator. The resulting set will be obtained by removing all the elements from
set 1 that are present in set 2.

Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}

Output:

{'Thursday', 'Wednesday'}

Set comparisons

Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the
sets by using which we can check whether a set is subset, superset, or
equivalent to other set.

The boolean true or false is returned depending upon the items present inside
the sets.

Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}

#Days1 is the superset of Days2 hence it will print true.


print (Days1>Days2)

#prints false since Days1 is not the subset of Days2


print (Days1<Days2)

#prints false since Days2 and Days3 are not equivalent


print (Days2 == Days3)

Output:

True
False
False

b) Illustrate class inheritance in Python with an example


 Python supports the concept of both multiple and multilevel
inheritance.
 Inheritance is the ability to define a new class that is a modified version
of an existing class.
 The new class inherits the members of the class it extends.
 When a new class inherits from an existing one, the existing one is
called the parent class(super-class) and the new class is called the child
class(sub-class).

Simple Inheritance
Inheritance can be achieved by passing the parent class as an argument in the
class definition of child class.

class Parent:
parentname = ""
childname = ""

def show_parent(self):
print(self.parentname)

# Child class created inherits Parent class


class Child(Parent):
def show_child(self):
print(self.childname)

ch1 = Child() # Object of Child class


ch1.parentname = "Arati" # Access Parent class attributes
ch1.childname = "Purva"
ch1.show_parent() # Access Parent class method
ch1.show_child()
Multiple Parent Classes
In multiple inheritance one child class can inherit multiple parent classes.

Example
Two parent classes Father and Mother extended by the child class
named Son.
# Father class created
class Father:
fathername = ""

def show_father(self):
print(self.fathername)

# Mother class created


class Mother:
mothername = ""

def show_mother(self):
print(self.mothername)

# Son class inherits Father and Mother classes


class Son(Father, Mother):
def show_parent(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)

s1 = Son() # Object of Son class


s1.fathername = "Mark"
s1.mothername = "Sonia"
s1.show_parent()

Multilevel Inheritance
In this type of inheritance, a class can inherit from a child class or derived
class.

Eg: Son class inherited from Father and Mother classes which derived
from Family class.
class Family:
def show_family(self):
print("This is our family:")
# Father class inherited from Family
class Father(Family):
fathername = ""
def show_father(self):
print(self.fathername)
# Mother class inherited from Family
class Mother(Family):
mothername = ""
def show_mother(self):
print(self.mothername)

# Son class inherited from Father and Mother classes


class Son(Father, Mother):
def show_parent(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
s1 = Son() # Object of Son class
s1.fathername = "Ashish"
s1.mothername = "Sonia"
s1.show_family()
s1.show_parent()

Call Parent Class Constructor from Child Class


In this type of inheritance parent class attributes initialized using child class
constructor.

Example
Inside the Father class constructor, the Family class constructor is called and
arguments for the Family class constructor are passed to it.
class Family:
# Parent class constructor
def __init__(self, name):
self.name = name

# Father class inherited from Family


class Father(Family):
# Child class constructor
def __init__(self, name, age):
# Parent class constructor called from child class
Family.__init__(self, name)
self.age = age

f = Father("Ashish", 36)
print(f.name)
print(f.age)

c) Design a class Employee with data members: name, department and


salary. Create suitable

methods for reading and printing employee information

You might also like