You are on page 1of 22

21UME503 - OBJECT ORIENTED PYTHON PROGRAMMING

3rd YEAR 5th SEMESTER

DEPARTMENT OF MECHANICAL ENGINEERING

COURSE MATERIAL

QUESTION PATTERN

PART A 10 x 2 Marks 20

PART B 5 x 6 Marks 30

PART C 5 x 10 Marks (Either or type) 50

Total Marks 100


SYLLABUS

21UME503 OBJECT ORIENTED PYTHON PROGRAMMING L T P C


3 0 0 3
COURSE OBJECTIVE:
 To acquire programming skills in core python
 To learn about the usage of python shell for running programs
 To understand the different data types available in python.
 To acquire object oriented skills in python
 To understand the creation and usage of various modules and packages.
UNIT I PYTHON FUNDAMENTALS AND DATA STRUCTURES 9

Introduction – Data types – Numbers – Variables – Strings – Lists – Dictionaries –


Tuples – Sets – Boolean – Basic I/O operations – Python Operators

UNIT II PYTHON STATEMENTS, METHODS AND FUNCTIONS 9

Decision Making – Loops – If, Else, Elif – While Loops – For Loops – Nested Loop –
Break – Continue Methods – Functions – Built in Functions

UNIT III MODULES PACKAGES AND LIBRARIES 9


Modules and Packages – Standard Libraries – Python Maths – Queues – FIFO
Queue – LIFO Queue – Priority Queue – Third Party Library – Numpy - Python
Arrays

UNIT IV OBJECT ORIENTED PROGRAMMING METHODOLOGIES 9


Object Oriented Programming – Creating Python Classes – Initializing Objects –
Python Object Recognition – Objects and Classes – Inheritance and its Types –
Basic Inheritance – Multiple Inheritance – Polymorphism
STRINGS FORMATING, FILE AND EXCEPTION
UNIT V 9
HANDLING
String Formatting – File Handling - Escaping Braces – Keyword Arguments –
Exception Handling – Raising Exception – Effects of Exception – Handling the
Exception – Exception Hierarchy – Creating our own Exceptions
Total : 45 Periods

Department of Mechanical Engineering, Sethu Institute of Technology Page 1


QUESTION BANK
PART A (2 Marks)
UNIT - I
1. ________ is the syntax used to get the input from the user. CO 1 - U -
(a) input( ) (b) int( ) (c) id( ) (d) iter( )
2. _____ character is used for the single-line comments in Python. CO 1 - U -
(a) // (b) # (c) ! (d) /*
3. _____is used to create an empty set in Python. CO 1 - U -
(a) () (b) [] (c) {} (d) set()
4. Write the output of the following Python function. CO 2 - Ap PO1
len(["hello", 2, 4, 6])
(a) Error (b) 3 (c) 6 (d) 4
5. ______ is the correct extension of the Python file. CO 1 - U -
(a) .python (b) .pi (c) .py (d) .p
UNIT - II
1. _______ is/are present in the function header. CO 1 - U -
a) function name b) keyword c) parameter list d) All the above
2. What will be the output of the following Python code? CO 2 - Ap PO1
x = 'abcd'
for i in x:
print(i.upper( ))
a) a b) a c) error d) A
B b B
C c C
D d D
3. _____ is a built-in function in python. CO 1 - U -
a) fact( ) b) print( ) c) power d) squareroot( )
4. ____ is the keyword used to specify the definition of the function. CO 1 - U -
a) def b) define c) fun d) function
5. Which of the following function header(s) is/are correct? CO 2 - Ap PO1
a) b) def area (a = 1, b, c c) d) All the above
def area (a = 1, b): = 2): def area (a = 1, b = 1, c
= 2):
UNIT - III
1. Output of round (4.576) is _____ CO 3 - Ap PO1
a) 4.5 b) 5 c) 4 d) 4.6
2. _____ function is used for transpose of an array in Numpy. CO 1 - U -
a) sum b) T c) matmul d) dot
3. Brief the queue type LIFO CO 1 - U -
a) First in first out b) First in last out c) Last in first out d) Last in last out
4. Which of the following file is used for package? CO 1 - U -
a) __str__.py b) __init__.py c) __len__.py d) __del__.py
5. The definition for packages in Python is _______ CO 1 - U -
a) A set of main b) A folder contains c) A number of files d) A set of
modules __init__ file and containing Python programs making
python modules definitions and use of Python
statements modules

Department of Mechanical Engineering, Sethu Institute of Technology Page 2


UNIT - IV
1. _________ is reference for an object. CO 1 - U -
a) class b) def c) self d) init
2. ______ defines the constructor method. CO 1 - U -
a) def __init__ (title, b) def __init__ (self, c) def __init__ ( ): d) __init__ (self,
author): title, author): title, author):
3. Which feature of OOPS derives the class from another class? CO 1 - U -
a) Inheritance b) Data hiding c) Encapsulation d) Polymorphism
4. How many objects and reference variables are there for the given CO 4 - Ap PO1
Python code?
class A:
print("Inside class")
A( )
A( )
obj=A( )
a) 2 and 1 b) 3 and 3 c) 3 and 1 d) 3 and 2
5. Which of the following is not an OOPS concept? CO 1 - U -
a) Encapsulation b) Polymorphism c) Exception d) Abstraction
UNIT - V
1. Which statement will read 5 characters from a file object „f‟? CO 1 - U -
a) f.read( ) b) f.read(5) c) f.reads(5) d) f.reading(5)
2. Which function is used to open the file in python? CO 1 - U -
a) open( ) b) OpeN( ) c) Open( ) d) OPEN( )
3. What will be output for the following code? CO 4 - Ap PO1
try:
print(x)
except:
print("An exception occurred")
a) x b) An exception c) Error d) None of the
occurred above
4. Which of the following string format is used for center alignment? CO 1 - U -
a) : > b) : < c) : ^ d) : =
5. What will be output for the following code? CO 4 - Ap PO1
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
a) x b) Something else c) Error d) Variable x is not
went wrong defined
PART - B (6 Marks)

UNIT - I
1. Define operators and briefly explain any 4 types of operators. CO 1 - U -
2. Write a program to calculate the area of a circle with radius value of CO 2 - AP PO1
10cm.
3. Compare tuples and list with syntax & examples. CO 1 - U -
4. Explain briefly about length of the string, string slicing, indexing with CO 1 - U -
examples.

Department of Mechanical Engineering, Sethu Institute of Technology Page 3


UNIT - II
1. Write a python program to print the word “WATERMELON” in vertical CO 2 - AP PO1
manner using for loop.
2. Explain any six built-in-functions with examples. CO 1 - U -
3. Explain briefly about if, elif and else statements with syntax. CO 1 - U -
4. Explain briefly about functions with example. CO 1 - U -
UNIT - III
1. Write a python program to find the following using math. CO 3 - AP PO1
(i) Square root for 169 (ii) 2 power 4
2. Write a python program to find the sin, cos, tan values of „0‟ degree CO 3 - AP PO1
using math.
3. Write a python program using python random module to shuffle the CO 3 - AP PO1
below list and print the original list and shuffled list.
List1 = [1, 2, 3, 4, 5]
4. Describe about packages in python. CO 1 - U -
UNIT - IV
1. Define a class square using side and compute the area of square using CO 4 - AP PO1
constructor method. Take side = 20 cm.
2. Define a class circle using radius and compute the area of circle using CO 4 - AP PO1
constructor method. Take radius = 10 cm.
3. Define a class rectangle using length and width and compute the area of CO 4 - AP PO1
rectangle using constructor method. Take length = 20 cm, width = 10
cm.
4. Define a class triangle using breadth and height and compute the area of CO 1 - U -
triangle using constructor method. Take breadth = 10cm, height = 25cm.
UNIT - V
1. Explain briefly about File Handling. CO 1 - U -
2. Explain briefly about string formats. CO 1 - U -
3. Explain Python notations with examples. CO 1 - U -
4. Explain briefly about Except Handling. CO 1 - U -
PART - C (10 Marks)
UNIT - I
1. Write a program to perform Addition, Subtraction, Multiplication, CO 2 - AP PO 1 (10)
Division, Modulus Division and Floor Division on two integer
numbers (9,6) and floating point numbers (10.7,6.3).
2. Input s1 = Mechanical s2 = Engineering CO 2 - AP PO 1 (10)
Print the following:
a) Length of String „Mechanical‟
b) Mechanical Engineering
c) Mech Eng
d) ME
e) MECHANICAL ENGINEERING
3. Write a python program to find the length of the lists, form matrix CO 2 - AP PO 1 (10)
from the lists and find the first column of the matrix from the given
lists:
List1 = [10,11,12]; List2 = [13,14,15]; List3 = [16,17,18]
4. Construct a dictionary with keys as Roll Nos. 101,102,103,104 and CO 2 - AP PO 1 (10)
values as marks 64,45,78,59.
(a) Print the roll no for 104
(b) There was a mistake in the marks of Roll no 102, kindly add 5
marks
Department of Mechanical Engineering, Sethu Institute of Technology Page 4
(c) Call all marks of the students
5. Write a Python program to create a dictionary of keys x, y, and z CO 2 - AP PO 1 (10)
where each key has as value a list from 11-20, 21-30, and 31-40
respectively.
(a) Access the fifth value of each key from the dictionary.
(b) Update the dictionary with the key „w‟ has the value of list
from 41-50.
(c) Call all the values from w, x, y and z.
UNIT - II
1. If 91 to 100 = S, 81 to 90 = A+, 71 to 80 = A, 60 to 70 = B+, 51 to CO 2 - AP PO 1 (10)
59 = B, <50 = RA. Find out grades for 75, 85, 95 using if elif and
else statements.
2. Write a python program to print cube of all numbers from 5 to 15 CO 2 - AP PO 1 (10)
and stop when cubed value reaches 1000 using While Loop.
3. Write a python program for creating a multiplication table for first CO 2 - AP PO 1 (10)
10 numbers using For Loop.
4. Write a shutdown program: CO 2 - AP PO 1 (10)
Define a function that takes one argument. If the function receives
"yes", it should return "Shutting down", "no", then it should return
"Shutdown aborted", if gets anything other than those inputs, it
should return "Sorry".
5. Define a function that create the list of roll numbers for present CO 2 - AP PO 1 (10)
students and write another function to check the status of the
students attendance by giving their roll no.
List of Roll No: 101, 102, 104, 105, 107, 108
Attendance checking Roll No: 102, 111
UNIT - III
1. Write a NumPy program to create the 2D array A & B and find the CO 3 - AP PO 1 (10)
addition of the two arrays and find the transpose for the output.
2. Write a python program to create an array using array module with CO 3 - AP PO 1 (10)
values 1-10.
(i) Display the array output 1-10
(ii) Update the array with value 11 at the 10th index
(iii) Call the 4th index value
3. Write a python queue program for the range of 8 and returns first in CO 3 - AP PO 1 (10)
first out.
4. Write a python queue program for the range of 11 to 20 and returns CO 3 - AP PO 1 (10)
last in first out.
5. Write a python queue program for the input of 8, 10, 14, 7, 9, 2 and CO 3 - AP PO 1 (10)
returns priority.
UNIT - IV
1. Write a program to create two classes for calculating stress and CO 4 - AP PO 1 (10)
strain by getting the input data from the user and use the output in
third class and calculate the Young‟s Modulus value.
2. Write a Python Program to define a class point3D using CO 4 - AP PO 1 (10)
„constructor‟ method and format using „repr‟ method.
3. Write a program for creating class student with rollno, name and CO 4 - AP PO 1 (10)
age using constructor method.
4. Write a Python Program to get the input of number of items and CO 4 - AP PO 1 (10)
value of the item and determine the total cost of the items.

Department of Mechanical Engineering, Sethu Institute of Technology Page 5


5. Write a program to create inheritance for derived function from CO 4 - AP PO 1 (10)
addition (addition of two numbers) and multiplication
(multiplication of two numbers) class to division class
(multiplication output / addition output).
UNIT - V
1. Write a Python String Format Program to draw a table with Left, CO 4 - AP PO 1 (10)
Centre and Right alignment for the given below values:
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
10 | 11 | 12
13 | 14 | 15
Also use “=” for Left Alignment, “#” for Centre Alignment and
“*” for Right Alignment.
2. Write a Python String Format Program to create a bill with items in CO 4 - AP PO 1 (10)
the first column, Price per unit in the second column, quantity in
the third column and total price in the fourth column. Also display
the total price amount of the items.
Item Price per unit Quantity Total Price
Item1 10 10 100
Item2 8 10 80
Item3 6 10 60
Total 30 240

3. Write a program to read a text file and rewrite as CO 4 - AP PO 1 (10)


“Hello
Welcome to MECH”.
4. Write a simple exception handling program for list addition. CO 4 - AP PO 1 (10)
List1 = [100, 200, 300, "400", 500]
List1 = [100, 200, 300, 400, 500]
5. Write a simple try and except program for the following outputs. CO 4 - AP PO 1 (10)
„No Error occurred‟
„ZeroDivisionError occurred and handled‟
'NameError occurred and handled'

Department of Mechanical Engineering, Sethu Institute of Technology Page 6


COURSE MATERIAL
PART – A
1. ________ is the syntax used to get the input from the user.
a) input( ) b) int( ) c) id( ) d) iter( )
2. _____ character is used for the single-line comments in Python.
a) // b) # c) ! d) /*
3. _____is used to create an empty set in Python.
a) () b) [] c) {} d) set()
4. Write the output of the following Python function.
len(["hello", 2, 4, 6])
a) Error b) 3 c) 6 d) 4
5. ______ is the correct extension of the Python file.
a) .python b) .pi c) .py d) .p
6. _______ is/are present in the function header.
a) function name b) keyword
c) parameter list d) all the above
7. ____ is the keyword used to specify the definition of the function.
a) def b) define c) fun d) function
8. Which of the following function header(s) is/are correct?
a) def area (a = 1, b): b) def area (a = 1, b, c = 2):
c) def area (a = 1, b = 1, c = 2): d) All the above
9. _____ is a built-in function in python.
a) fact( ) b) print( ) c) power( ) d) squareroot( )
10. What will be the output of the following Python code?
x = 'abcd'
for i in x:
print(i.upper( ))
a) a b) a c) error d) A
B b B
C c C
D d D
11. Output of round (4.576) is _____
a) 4.5 b) 5 c) 4 d) 4.6
12. The definition for packages in Python is _______
a) A set of main modules
b) A folder contains __init__ file and python modules
c) A number of files containing Python definitions and statements
d) A set of programs making use of Python modules
13. _____ function is used for transpose of an array in Numpy.
a) sum b) T c) matmul d) dot
14. Brief the queue type LIFO.
a) First in first out b) First in last out c) Last in first out d) Last in last out

Department of Mechanical Engineering, Sethu Institute of Technology Page 7


15. Which of the following file is used for package?
a) __str__.py b) __init__.py c) __len__.py d) __del__.py
16. _________ is reference for an object.
a) class b) def c) self d) init
17. ______ defines the constructor method.
a) def __init__ (title, author): b) def __init__ (self, title, author):
c) def __init__ ( ): d) __init__ (self, title, author):
18. Which of the following is not an OOPS concept?
a) Encapsulation b) Polymorphism
c) Exception d) Abstraction
19. Which feature of OOPS derives the class from another class?
a) Inheritance b) Data hiding
c) Encapsulation d) Polymorphism
20. How many objects and reference variables are there for the given Python code?
class A:
print("Inside class")
A( )
A( )
obj=A( )
a) 2 and 1 b) 3 and 3 c) 3 and 1 d) 3 and 2
21. Which statement will read 5 characters from a file object „f‟?
a) f.read( ) b) f.read(5) c) f.reads(5) d) f.reading(5)
22. Which function is used to open the file in python?
a) open( ) b) OpeN( ) c) Open( ) d) OPEN( )
23. What will be output for the following code?
try:
print(x)
except:
print("An exception occurred")
a) x b) An exception occurred
c) Error d) None of the above
24. Which of the following string format is used for center alignment?
a) : > b) : < c) : ^ d) : =
25. What will be output for the following code?
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
a) x b) Something else went wrong
c) Error d) Variable x is not defined

Department of Mechanical Engineering, Sethu Institute of Technology Page 8


PART – B
UNIT - I
1. Define operators and briefly explain any 4 types of operators.
Operators are used to perform operations on variables and values. Python
divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators
Arithmetic operators
Addition (+) a+b
Subtraction (-) a–b
Multiplication (*) a*b
Division (/) a/b

Assignment operators
= x=5
+=  x = x+3
-=  x = x-3
*=  x = x*3

Comparison operators
Equal (==)  x == y
Not Equal (!=)  x != y
Greater than (>)  x >y
Less than (<)  x <y

Logical operators
and  x < 5 and x < 10
or  x < 5 or x < 4
not  not(x < 5 and x < 10)

2. Write a program to calculate the area of a circle with radius value of 10cm.
Program:
r = int(input(“Enter the radius value:”))
a = 3.14*r*r
print(“Area of the Circle is: ”,a,“ sq.m”)
Output:
Enter the radius value: 4
Area of the Circle is: 50.24 sq.m

Department of Mechanical Engineering, Sethu Institute of Technology Page 9


3. Compare tuples and list with syntax & examples.
Tuples:
In Python tuples are very similar to lists, however, unlike lists they are
immutable meaning they cannot be changed. You would use tuples to
present things that shouldn't be changed, such as days of the week, or
dates on a calendar. We can treat them very similarly with the major
distinction being that tuples are immutable.

Tuples are constructed by () with elements separated by commas.


For example:
t = (1,2,3)
t1 = („one‟,2,3)

It can‟t be stressed enough that tuples are immutable. That is we can‟t


add or edit the tuple. Then it may be a wonder that why bother using
tuples when they have fewer available methods. Because to be honest,
tuples are not used as often as lists in programming, but are used when
immutability is necessary. In in a program an object was passing around
and need to make sure it does not get changed, then a tuple becomes the
solution. It provides a convenient source of data integrity.
For example:
t = („Sunday‟, „Monday‟, „Tuesday‟, „Wednesday‟, „Thursday‟, „Friday‟,
„Saturday‟)

Lists:
Lists can be thought of the most general version of a sequence in
Python. Unlike strings, they are mutable, meaning the elements inside a
list can be changed! Lists are constructed with brackets [] and commas
separating every element in the list.
For example:
list1 = [1,2,3]
list2 = [„Mechanical‟, „Engineering‟]

Unlike tuples, in list items can be added or edited using concatenation


and slicing functions. List can also be used as arrays.
A great feature of Python data structure is that they support nesting.
This means an input can have data structures within data structures that
is a list inside a list is called nested list.
For Example:
list1 = [1,2,3]
list2 = [4,5,6]
list3 = [7,8,9]
matrix = [list1, list2, list3]
print(matrix)
Output: [[1,2,3], [4,5,6], [7,8,9]]

Department of Mechanical Engineering, Sethu Institute of Technology Page 10


4. Explain briefly about length of the string, string slicing, indexing with examples.
Strings are used in Python to record text information, such as names.
Strings in Python are actually a sequence, which basically means Python
keeps track of every element in the string as a sequence For example,
Python understands the string “hello” to be a sequence of letters in a
specific order. This means we will be able to use indexing to grab
particular letters (like the first letter, or the last letter)
Length of the String:
Length of the string is a function to count the number of characters
presented in a string. The syntax to determine the length of the string is
len().
Example:
a = “Mechanical Engineering”
c = len(a)
print(“The length of the string is ”,c)
Output:
22
String Indexing:

In Python, strings are ordered sequences of character data, and thus


can be indexed in this way. Individual characters in a string can be
accessed by specifying the string name followed by a number in square
brackets ([]). String indexing in Python is zero-based: the first character in
the string has index 0, the next has index 1, and so on. The index of the
last character will be the length of the string minus one.

P Y T H O N
0 1 2 3 4 5

Example:
a = “Python”
b = a[0]
c = a[1]
d = a[2]
e = a[3]
print("Print the 0th index: ",b)
print("Print the 1st index: ",c)
print("Print the 2nd index: ",d)
print("Print the 3rd index: ",e)
Output:
Print the 0th index: P
Print the 1st index: y
Print the 2nd index: t
Print the 3rd index: h

String Slicing:
String slicing is used to grab everything from a string up to a
designated point. Slicing can be done by using : within the [] bracket

Department of Mechanical Engineering, Sethu Institute of Technology Page 11


Example:
a = “Mechanical Engineering”
b = a[1:]
c = a[:3]
d = a[-1]
e = a[:-1]
f = a[::2]
g = a[::-1]
print(“Print except the first letter: ”,b)
print(“Print up to the third index: ”,c)
print(“Print only the last letter: ”,d)
print(“Print except the last letter: ”,e)
print(“Print the string but go in step size of 2: ”,f)
print(“Print the string in reverse order: ”,g)
Output:
Print except the first letter: echanical Engineering
Print up to the third index: Mec
Print only the last letter: g
Print except the last letter: Mechanical Engineerin
Print the string but go in step size of 2: Mcaia niern
Print the string in reverse order: gnireenignE lacinahceM

UNIT - II
1. Write a python program to print the word “WATERMELON” in vertical manner using for
loop.
Program:
a = int(input(“Enter the word:”))
b=len(a)
for i in range(1,b+1):
print(i)
Output:
Enter the word: WATERMELON
W
A
T
E
R
M
E
L
O
N

Department of Mechanical Engineering, Sethu Institute of Technology Page 12


2. Explain any six built-in-functions with examples.
print( ):
The python print( ) function prints the given object to the screen or other standard output
devices.
print(“Welcome”)  “Welcome”
len( ):
The python len( ) function is used to return the length (the number of items) of an object.
len([10,15,20,25])  4
max( ):
The python max( ) function is used to return the largest item in an iterable or the largest
of two or more arguments.
max([10,15,20,25])  25
min( ):
The python min( ) function is used to return the smallest item in an iterable or the
largest of two or more arguments.
max([10,15,20,25])  10
round( ):
The python round( ) function rounds off the digits of a number and returns the floating
point number.
print(round(6.6))  7
input( ):
Python input( ) function is used to get an input from the user. It prompts for the user
input and reads a line. After reading data, it converts it into a string and returns it. It
throws an error EOFError if EOF is read.
val = input("Enter a value: ")  Enter a value: 45
range( ):
The python range( ) function returns an immutable sequence of numbers starting from 0
by default, increments by 1 (by default) and ends at a specified number.
print(list(range(1,7 )))  [1, 2, 3, 4, 5, 6]
pow( ):
The python pow( ) function is used to compute the power of a number. It returns x to the
power of y. If the third argument(z) is given, it returns x to the power of y modulus z, i.e.
(x, y) % z.
print(pow(4, 2))

Department of Mechanical Engineering, Sethu Institute of Technology Page 13


3. Explain briefly about if, elif and else statements with syntax.
Syntax:
if condition1:
code block 1

elif condition2:
code block 2

else:
code block 3

Where,
If condition1 evaluates to true, code block 1 is executed.
If condition1 evaluates to false, then condition2 is evaluated.
If condition2 is true, code block 2 is executed.
If condition2 is false, code block 3 is executed.

Example:
Program:
a=0
if a > 0:
print("Positive number")
elif a < 0:
print(''Negative number')
else:
print('Zero')

Output:
Zero

4. Explain briefly about functions with example.


Program:
def shut_down(s):
if s=='yes':
print('Shutting down')
elif s=='no':
print('Shutdown aborted')
else:
print('Sorry')
shut_down('yes')
shut_down('no')
shut_down('cancel')

Output:
Shutting down
Shutdown aborted
Sorry

Department of Mechanical Engineering, Sethu Institute of Technology Page 14


UNIT - III
1. Write a python program to find the following using math.
(i) Square root for 169 (ii) 2 power 4
Program:
import math
print("Square root value is: ",math.sqrt(169))
print("The power value is: ",math.pow(2,4))
Output:
Square root value is: 13.0
The power value is: 16.0
2. Write a python program to find the sin, cos, tan values of „0‟ degree using math.
Program:
import math
a=0
print("sin 0 is:", math.sin(a))
print("cos 0 is:",math.cos(a))
print("tan 0 is:",math.tan(a))
Output:
sin 0 is: 0.0
cos 0 is: 1.0
tan 0 is: 0.0
3. Write a python program using python random module to shuffle the below list and print the
original list and shuffled list. List1 = [1, 2, 3, 4, 5]

Program:
import random
List1 = [1, 2, 3, 4, 5, 6, 7]
print("The original list is: ",List1)
random.shuffle(List1)
print("The shuffled list is: ",List1)

Output:
The original list is: [1, 2, 3, 4, 5]
The shuffled list is: [2, 4, 5, 3, 1]

Department of Mechanical Engineering, Sethu Institute of Technology Page 15


4. Describe about packages in python.
A directory must contain a file named __init__.py in order for Python to consider it
as a package. This file can be left empty but we generally place the initialization code for
that package in this file.

UNIT - IV
1. Define a class square using side and compute the area of square using constructor method.
Take side = 20 cm.
Program:
class Square:
def _ _init_ _(self):
self.L = int(input("Enter Length Value: "))
self.A = self.L * self.L
print("The Area of square is: ",self.A,"sq.cm")
obj = Square()
Output:
Enter Length Value: 20
The Area of square is: 40.0 sq.cm

Department of Mechanical Engineering, Sethu Institute of Technology Page 16


2. Define a class circle using radius and compute the area of circle using constructor method.
Take radius = 10 cm.
Program:
class Circle:
def _ _init_ _(self):
self.r = int(input("Enter Radius Value: "))
self.A = 3.14 * self.r * self.r
print("The Area of circle is: ",self.A,"sq.cm")
obj = Circle( )
Output:
Enter Radius Value: 10
The Area of circle is: 314.0 sq.cm

3. Define a class rectangle using length and width and compute the area of rectangle using
constructor method. Take length = 20 cm, width = 10 cm.
Program:
class Rectangle:
def _ _init_ _(self):
self.L = int(input("Enter Length Value: "))
self.W = int(input("Enter Width Value: "))
self.A = self.L * self.W
print("The Area of rectangle is: ",self.A,"sq.cm")
obj = Rectangle( )
Output:
Enter Length Value: 20
Enter Width Value: 10
The Area of rectangle is: 200 sq.cm

Department of Mechanical Engineering, Sethu Institute of Technology Page 17


4. Define a class triangle using breadth and height and compute the area of triangle using
constructor method. Take breadth = 10cm, height = 25cm.
Program:
class Triangle:
def _ _init_ _(self):
self.B = int(input("Enter Breadth Value: "))
self.H = int(input("Enter Height Value: "))
self.A = 0.5* self.B * self.H
print("The Area of triangle is: ",self.A,"sq.cm")
obj = Triangle( )
Output:
Enter Breadth Value: 1
Enter Height Value: 1
The Area of triangle is: 0.5 sq.cm

UNIT - V

1. Explain briefly about File Handling.


Opening a file:
 To open a file in Python, we use the open() function.
 The syntax of open() is as follows:
file_object= open(file_name, access_mode)
f = open(„demo.txt‟, „r‟)
Closing a file:
 Once we are done with the read/write operations on a file, it is a good
practice to close the file.
 Python provides a close() method to do so. While closing a file, the
system frees the memory allocated to it.
 The syntax of close() is:
file_object.close()
f.close()
Rewriting a file:
 write() method takes a string as an argument and writes it to the text
file.
 It returns the number of characters being written on single execution
of the write() method.
file_object= open(file_name, access_mode)
f = open(„demo.txt‟, „w‟)

Department of Mechanical Engineering, Sethu Institute of Technology Page 18


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(„demo.txt‟, „x‟)
2. Explain briefly about string formats.
There are three ways to perform string formatting.
 The oldest method involves placeholders using the modulo %
character.
 An improved technique uses the .format() string method.
 The newest method, introduced with python 3.6, uses formatted string
literals, called f-strings.
% Character method: (%s, %c, %i)
a = 'Rohit'
b = 'SIT'
print('My name is %s' %a)
print('My college name is %s' %b)
Output:
My name is Rohit
My college name is SIT

.Format method:
print('{0:<8} {1:^8} {2:>8}'.format(1,2,3))
print('{0:<8} {1:^8} {2:>8}'.format(4,5,6))
print('{0:<8} {1:^8} {2:>8}'.format(7,8,9))
Output:
1 2 3
4 5 6
7 8 9

F-string method:
x = 'John'
print(f'He said his name is {x}')

Output:
He said his name is John
Department of Mechanical Engineering, Sethu Institute of Technology Page 19
3. Explain Python notations with examples.

4. Explain briefly about Except Handling.


 Error in Python can be of two types i.e. Syntax errors and Exceptions.
 Errors are the problems in a program due to which the program will
stop the execution.
 On the other hand, exceptions are raised when some internal events
occur which changes the normal flow of the program.
Syntax Error
As the name suggests this error is caused by the wrong syntax in the code.
It leads to the termination of the program.

Department of Mechanical Engineering, Sethu Institute of Technology Page 20


Exceptions:
Exceptions are raised when the program is syntactically correct, but the
code resulted in an error. This error does not stop the execution of the
program, however, it changes the normal flow of the program.

Handling an exception:
 If you have some suspicious code that may raise an exception, you
can defend your program by placing the suspicious code in
a try: block. After the try: block, include an except: statement,
followed by a block of code which handles the problem.
 Try and except statements are used to catch and handle exceptions
in Python. Statements that can raise exceptions are kept inside the try
clause and the statements that handle the exception are written inside
except clause.
Example Program:

Department of Mechanical Engineering, Sethu Institute of Technology Page 21

You might also like