Python Programming: Time: 2 HRS.) (Marks: 75
Python Programming: Time: 2 HRS.) (Marks: 75
III
Python Programming
Time : 2½ Hrs.] Prelim Question Paper Solution [Marks : 75
-1-
BSC IT PRO : T.Y. B.Sc. (IT) PP
Flow diagrams:
Example :
temp = float (input (“what is the temperature”))
iftemp > 48: Condition
True
Q.1 (e) What is the difference between interactive mode and script mode in Python? [5]
Ans.: Python has 2 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 like shell which gives immediate feedback for each statement, while running
previously fed statements in active memory.
Interactive Mode : In this mode Python displays the result of expressions. It allows
interactive testing and debugging of snippets of code.
Example: >>> print(57)
35
Script Mode : In a script mode code is written in a separate file and it is saved with an
extension .py. Then it can be executed by selecting ‘Run module’ option from Run Menu.
(Shortcut F5)
Example : File name is \.py
a = 10
if (a > 5);
-2-
Prelim Question Paper Solution
print(“Greater”)
else :
Print(“Smaller”)
Output :
Greater
Q.1 (f) Explain the use of break statement in a loop with example. [5]
Ans.: The break statement terminates the loop containing it. Control of the program flows to the
statement immediately after the body of the loop.
If break statement is inside a nested loop, breaks will terminate the innermost loop.
Syntax :
break
Example : Program to find out whether the input number is prime or not.
n = int(input(“Enter a no.”))
for i in range(2, n+1):
if n% i ==0:
break
if i == n:
print(n, ‘is prime’)
else:
print(n, ‘is not prime’)
Output :
1st Run Enter
a no. 5 5
is prime 2nd
Run
Enter a no 10
10 is not prime
-3-
BSC IT PRO : T.Y. B.Sc. (IT) PP
Q.2 (a) (iii) Fermat’s Last Theorem says that there are no positive integers a, b, and [5]
c such that an + bn = cn for any values of n greater than 2.
Write a function named check_fermat that takes four parameters—a, b, c
and n—and that checks to see if Fermat’s theorem holds. If n is greater
than 2 and it turns out to be true that an + bn = cn the program should
print, “Holy smokes, Fermat was wrong!” Otherwise the program should
print, “Fermat’s Theorem holds.”
Write a function that prompts the user to input values for a, b, c and n,
converts them to integers, and uses check_fermat to check whether they
violate Fermat’s theorem
Ans.: def check_fermat (a, b, c, n) :
if n > 2 :
if (a ** n + b ** n == c**n :
print (“Holy smokes, fermat was wrong!”)
else :
print (“a ** {0} + b ** {0} == c** {0} is false” . format (n))
elif (a**n + b**n) == c**n :
print (“fermat’s theorem holds”)
else :
print (“a**{0} + b**{0} == c**{0} is false” .fermat(n))
def f() :
a = int (input (‘a = ’))
b = int (input (‘b = ’))
c = int (input (‘c = ’))
n = int (input (‘n = ’))
check_fermat (a, b, c, n)
-4-
Prelim Question Paper Solution
Q.2 (b) (i) Write the output for the following if the variable fruit = 'banana' : [5]
>>> fruit[:3]
>>> fruit[3:]
>>> fruit[3:3]
>>> fruit[:]
Ans.: fruit = ‘banana’ :
>>> fruit [:3]
‘ban’
>>> fruit [3:]
‘ana’
>>> fruit [3:3]
‘ ’
>>> fruit [:]
‘banana’
Q.2 (b) (ii) What is the reason for the error seen here? [5]
>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: 'str' object does not support item assignment
Ans.: >>> greeting = ‘Hellow.world!’
>>> greeting [0] = ‘J’
It will show error because strings or immutable. We cannot change an existing string.
Q.2 (b) (iii) Explain any 2 methods under strings in Python with suitable examples.
Ans.: (a) Concatenation operation is done with the + operator in Python. Concatenation means
joining the string by linking the last end of the first string with the first end of the
second string. Two separate strings transform into the one single string after
concatenation.
(b) Repetition operation is performed on the strings in order to repeat the stings several
times. It is done with * operator.
>>> ‘Hello’ * 3
HelloHelloHello o/p
Step 1: Establish the input output. In this case the r is the input which can represent using
one parameter. The return value is the area, which is floating point value.
Step 2: Build the code block that calculates the area of a circle.
>>> defcarea(r) :
Output 0.0
return 0.0
It doesn’t compute. It always return 0 but it is syntactically correct and we context
syntax before we make it more complicated.
Step 3: Now apply formula (3.14*r*r)
>>> def carea(r)
return 3.14*r*r
Parameters:
str This specifies the string to be searched.
beg This is the starting index, by default its 0.
end This is the ending index, by default its equal to length of the string.
Return value
Index if found and 1 otherwise
Example :
str1 = “This is University of Mumbai”;
str2 = “Uni”
print(str1.find(str2))
print(str1.find(str2, 10))
print(str1.find(str2, 40))
Output:
8
1
1
Q.2(e) Write a Python code to check whether the given number is a strong number. [5]
Strong Numbers are numbers whose sum of factorial of digits is equal to the
original number (Example: 145 = 1! +4! + 5!) .
Ans.: def strongno (n) :
n1 = n
a=0
while n! = 0 :
d = n% 10
i=1
f=1
while i < = d :
f=f*i
i=i+1
s=s+fn
= n// 10
if s == n! :
print (“{0} is a strong No” . format(n1))
-6-
Prelim Question Paper Solution
else :
print (“{0} is not a strong No” . format (n1))
output
>>> strongno (145)
145 is a strong No
2. >>> [1, 2, 3] * 3
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
2. extend it takes list as an argument and appends all of the elements
>>> t1 = [‘a’, ‘b’, ‘c’]
>>> t2 = [‘d’, ‘e’]
>>> t1 . extend (t2)
>>> print t1
o/p [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
-8-
Prelim Question Paper Solution
Q.3 (d) What is tuple in Python? How to create and access it? [5]
Ans.: A tuple is a sequence of immutable Python objects. Tuples are sequences, just like list. The
differences between tuples and lists are, the tuples cannot be changed unlike list and tuples
use parentheses whereas list use square brackets.
To creat tuple use () parentheses and values must be commaseparated.
Eg. tup1 = (‘physics’, chemistry’, 1900, 2000)
tup2 = (1, 2, 3, 4, 5)
tup3 = “a”, “b”, “c”
like string indices, tuple indices start at 0, and they can be sliced, concentrated and so on.
To access values in tuple:
To access values in tuple, use the square brackets for slicing along with the index or indices
to obtain value available at that index. For example
tup1 = (‘Phy’, ‘che’, 1900, 2000)
tup2 = (1, 2,3,4, 5, 6, 7)
print “tup1[0]:”, tup1[0]
print “tup2[1:5]:”, tup [1:5]
Output :
tup1[0]: phy
tup2[1:5]: [2, 3, 4, 5]
Q.3 (e) Explain open ( ) and close ( ) methods for opening and closing file. [5]
Ans.: Python has built in function open () to open a file. This function returns a file object also
called a handle as it is used to read or modify the file accordingly.
Syntax :
obj = open (“path of file” [mode])
The default is reading in text mode.
Following are the file modes
Mode Description
r Open a file for reading (default)
w Open a file for writing.
x Open a file for exclusive creation.
a Open for appending at the end of file
b Open in binary mode
t Open in text mode (default)
+ Open a file for updating (read and write)
close() file
when we are done with operations to the file, we need to properly close the file. Closing a
file will free up the resources that were tied with the file and is done using Python closes
method.
f = open (“test.txt”)
# perform file operations
f.close()
-9-
BSC IT PRO : T.Y. B.Sc. (IT) PP
Q.3 (f)Write short note on Tuple Assignment (Packing and Unpacking) [5]
Ans.: Tuple Assignment: A tuple of variables on the left of an assignment can be assigned values
from a tuple or the right of the assignment.
- 10 -
Prelim Question Paper Solution
Types of inheritance
Single inheritance
Class
A
Class
B
Multilevel inheritance
Class
A
Class
B
Class
C
Class
A
- 11 -
BSC IT PRO : T.Y. B.Sc. (IT) PP
Class Class
A B
Class
C
# super class
Class person:
def _init_(self, name, age);
self.name = name
elf.age = age
def get_info(self);
return(self.name + “ “ + str(self.org))
def is employee (self);
returns false class
Employee
(person); def is
Employee(salf);
return true
emp = person(“xyz”, 10)
point (emp.getinfo( ). Emp is employee( ))
output
xyz 10 false
PQR 20 true
- 13 -
Prelim Question Paper Solution
Output 6
Here parent class has get_valve(self) method and the child class also have the same
method.
C is a abject of child class which calls the Derived class version of the method overiding the
parent class.
(ii) isinstance( ) it returns true if the object is an instance of the class or other classes
derived from it.
Isinstance( ) also checks whether a class in a subction or not.
Every class in python inherits from the bare class object.
Example :
import re
line = “cats are smarter than dogs”
obj = re. match (r % *) are (. * ?) *’, line /re. M\re.l)
if obj:
print “matchobj.group (1) :”, obj.group (1)
print “matchobj.group (2) :”, obj.group (2)
else:
print “No match”
Output:
match obj.group (1) : cats
match obj.group (2) : smarter
Q.4 (e) What is module? What are the advantages of using module? [5]
Ans.: Module A module allows you to logically organize your Python code. Grouping related code
into a module makes the code easier to understand and use. A module is a python object
with arbitrarily named attributes that you can bind and reference.
Simply a module is a file consisting of python code. A module can define functions, classes
and variables. A module can also include runnable code.
- 14 -
BSC IT PRO : T.Y. B.Sc. (IT) PP
import math :
print (“flour output =”, math.floor (1000.5))
print (“ceil output =”, math.ceil (1000.5))
print (“trunc output =”, math.trunc (123.45))
print (“power output =”, math.pow (2,3))
print (“square root output =”, math.sart (9))
print (“absolute output = “, math.fabs (123.5))
Output :
floor output = 1000 ceil
output = 1001
trunc output = 123
power output = 8.0
square root output = 3.0
absolute output = 123.5
Error
Question OK
- 15 -
Prelim Question Paper Solution
Output :
Id : 1, Adhaar No.: 700, Name : Geeta, Dept : VSIT, Age : 34
Id : 2, Adhaar No.: 800, Name : Babita, Dept : VSIT, Age : 35
Id : 3, Adhaar No.: 900, Name : Sunita, Dept : VSIT, Age : 37
Where,
Master This represents the parent window.
Option Here is the list of most commonly used options for this widget. These options can
be used as key value pairs separated by commas.
Example:
From Tkinter import *
Import theMessageBox
import Tkinter
- 16 -
BSC IT PRO : T.Y. B.Sc. (IT) PP
Top = Tkinter . Tk ()
VC1 = Intvar ()
VC2 = Intvar ()
C1 = Checkbutton (top, text = “Music”, variable = VC1, onvalue = 1,
offvalue = 0, height = 5, width = 20)
C2 = Checkbutton (top, text = “Video”, variable = VC2, onvalue = 1,
offvalue = 0, height = 5, width = 20)
C1 . pack ()
C2 . pack ()
tk X
Music
Video
Cursors are created by the connection. Cursor () method they are bound to the connection
for the entire lifetime and all the commands are executed in the context of the db session
wrapped by the connection.
Methods
open () opens the cursor.
close () closes the cursor.
fetchone () This method retrieves the next row of a query result set and returns
single sea or home if no more rows are available.
Pack Manager The pack geometry manager packs widgets in rows or columns. You can use
options like fill, expand and side to control this.
- 17 -
Prelim Question Paper Solution
Syntax :
widget.pack (pack_options)
where
expand when set to true, widget expands to fill any space not otherwise used in
widgets parent.
fill Determines whether widget fills any extra space allocated to it by the packer, or
keeps its own minimal dimensions : None, X (horizontal), V(vertical), or both (horizontal
& vertical)
Side Determines which side of the parent widget packs against : Top (default,
bottom, left or right.
Example : b1 = Button (frame, text = “red”)
b1.pack (side = LEFT)
Radio buttons are named after the physical buttons used on old radios to select wave bands
or preset radio stations. If such a button was pressed, other buttons would pop out, leaving
the pressed button the only pushed in button.
Each group of Radio button widgets has to be associated with the same variable. Pushing a
button changes the value of this variable to a predefined certain value.
root = tk.Tk ( )
v = tk.IntVar( )
tk.Label (root,
text = “ ” ”Choose a
programming language:” “ “,
justify = tk.LEET,
padx = 20) . pack( )
tk.Radiobutton (root,
text = “Python”,
padx = 20,
variable = v,
value = 1) pack (anchor = tk.w)
tk.Radiobutton (root,
text = “Perl”,
padx = 20,
variable = v,
value = 2) . pack (anchor=tk.w)
root.mainloop( )
- 18 -