Professional Documents
Culture Documents
Model Answer Paper
Model Answer Paper
……………………………………………………………………………………………………………………
…………………………………
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.
c) Describe Dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
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.
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
>>>
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
>>>
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")
i=0
First_Value = 0
Second_Value = 1
else:
First_Value = Second_Value
Second_Value = Next
print(Next)
i=i+1
o/p
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
(1, 2, 3, 4, 5)
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.
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
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
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
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
Read a File
The read() method is used to read files.
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:
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()
f = open("demofile.txt", "x")
f.close()
f = open("demofile_1.txt", "a")
f.close()
f = open("demofile_1.txt", "w")
f.close()
class Parent:
def echo(self):
print('I am from Parent class')
p = Parent()
c = Child()
p.echo()
c.echo()
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)
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
with open("1.py") as f:
for line in f:
f1.write(line)
divide(3, 0)
>>>fruit[:3]
>>>fruit[3:]
>>>fruit[3:3]
>>>fruit[:]
ban
ana
banana
Numbers
Integers, floating point numbers and complex numbers fall under Python
numbers category.
t = (5,'program', 1+3j)
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}
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}
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
1. >>> a=[1,2,3]
>>>b=[4,5,6]
>>> c=a+b
[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
t=[‘a’,’b’,’c’,’d’,’e’,’f’]
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.
Set operations
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.
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()
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:
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.
Output:
{'Martin', 'David'}
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.
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.
Output:
True
False
False
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)
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)
def show_mother(self):
print(self.mothername)
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)
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
f = Father("Ashish", 36)
print(f.name)
print(f.age)