Lab Manual-PCC-CS393
Lab Manual-PCC-CS393
[PCC-CS393]
LAB MANUAL
III SEMESTER
Laboratory Manual
1. All students must observe the Dress Code while in the laboratory.
2. Sandals or open-toed shoes are NOT allowed.
3. Foods and drinks are NOT allowed.
4. All bags must be left at the indicated place.
5. Be PUNCTUAL for your laboratory session.
6. Topic must be completed within the given time.
7. Noise must be kept to a minimum.
8. Handle all equipment with care.
9. All students are liable for any damage due to their own negligence.
10. Students are strictly PROHIBITED from taking out any items from the laboratory.
11. Report immediately to concern teachers if any injury occurred.
12. Report immediately to concern teachers any damages to equipment.
13. Report immediately to concern teachers for any equipment malfunctioning
14. Do not cut unnecessary wire lengths. Try to reuse wire pieces.
15. While removing /placing IC from /in be very careful to avoid teeth break/bends of IC.
Laboratory Manual
1. Course Information:
2. Institute Vision:
Emerge as a center of excellence for engineering and management studies encouraging research and
building leaders contributing towards individual and social empowerment.
3. Institute Mission:
To identify individual potential, capabilities and skills to achieve confidence and competence.
To practice innovative and modern methods of pedagogy encouraging holistic education and research.
To enhance employability skills through collaborative ventures with the industry.
To build leaders and entrepreneurs with integrity and ethics fostering growth and sustainability.
4. Departmental Vision:
To nurture and motivate students towards imbibing the essentials of Information Technology and explore their potentials
in IT industries & ITeS for addressing societal causes.
5. Departmental Mission:
Laboratory Manual
6. Program Educational Objectives (PEOs):
PEO1: To contribute in excellence of IT and IT-enabled services.
PEO2: To implement concepts of IT in different areas of problem solving.
PEO3: To communicate new ideas for effective implementation.
PEO4: To facilitate students for professional challenges.
PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and
an engineering specialization to the solution of complex engineering problems.
PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
PO3: Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental considerations.
PO4: Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools including prediction and modeling to complex engineering activities with an understanding of
the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
PO7: Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
PO9: Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear instructions.
Laboratory Manual
PO11: Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
PO12: Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
9. Syllabus:
Laboratory Topics:
Basic fundamental of Python
1 Working with Python, Basic Syntax, Variable and Data Types, Operator
Conditional Statements
2 If, If- else, Nested if-else, Looping, For, While, Nested loops
Control Statements
3 Break, Continue, Pass
String Manipulation
4 Accessing Strings, Basic Operations, String slices, Function and Methods
Lists
5 Introduction, Accessing list, Operations, Working with lists, Function and
Methods
Tuple
6 Introduction, Accessing tuples, Operations, Working, Functions and Methods
7 Set
Introduction, Create and accessing set element, Indexing and slicing
Dictionaries
8 Introduction, Accessing values in dictionaries, working with dictionaries,
Properties
Functions
9 Defining a function, Calling a function, Types of functions, Function
Arguments, Anonymous functions, Global and local variables
Laboratory Manual
Module
Importing module, Math module, Random module, Packages, Composition,
10 Input-Output Printing on screen, Reading data from keyboard, Opening and
closing file, Reading and writing files, Functions
Exception Handling
11 Exception, Exception Handling, Except clause, Try? finally clause, User
Defined Exceptions.
12 Class, Object, Inheritance
Implementation of Object oriented concepts
To understand of the scripting & the contributions of scripting using keywords, loops, array etc.
To apply different types of lists, tuple, set and dictionaries for solution of problem.
To understand functions, modules, Object oriented concept, exceptions for problem’s solution.
Laboratory Manual
12. Course Outcomes:
Apply the characteristics of scripts and basics elements of Python like conditional statements,
PCC-CS393.1
loops, control statements and String.
Make use of the knowledge of Python in different sample problems using Lists, Tuples, set and
PCC-CS393.2
Dictionaries.
PCC-CS393.3 Analyze sample problems using functions and modules.
PCC-CS393.4 Evaluate problems with different exceptions using except clause, try and finally clause.
13. Topic:
TABLE OF CONTENTS
5. Lists 16-18
6. Tuple 19-20
7. Set 21-24
8. Dictionaries 25-26
9. Functions 27-28
Laboratory Manual
Topic No. 1
Indentation:
Python uses indentation for blocks, instead of curly braces. Both tabs and spaces are supported, but the standard
indentation requires standard Python code to use four spaces.
Example:
x=1
if x == 1:
# indented four spaces
print("x is 1.")
Comment Line:
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of
the physical line are part of the comment and the Python interpreter ignores them.
Example:
#!/usr/bin/python
# First comment
print "Hello, Python!" # second comment
Laboratory Manual
Python Operators:
Python Operators are used to manipulate the value of variables or operands. Python language supports 7 types of
basic operators.
e=a*b
/ Division
print(d)
f=a*b
% Modulo
print(f)
** Exponent 2**3=8
Laboratory Manual
Topic No. 2
Conditional Statements
Decision making is the most important aspect of almost all the programming languages. As the name implies,
decision making allows us to run a particular block of code for a particular decision
1. If Statement: The if statement is used to test a specific condition. If the condition is true, a block of code (if-
block) will be executed.
The syntax of the if-statement is given below.
if expression:
statement
Example:
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")
Output:
enter the number?10
Number is even
2. If - else Statement: The if-else statement is similar to if statement except the fact that, it also provides the
block of the code for the false case of the condition to be checked. If the condition provided in the if statement is
false, then the else statement will be executed.
Example:
# python program to illustrate If else statement
#!/usr/bin/python
i =20;
if(i< 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
3. Nested if Statement: Nested if statements enable us to use if /else statement inside an outer if statement. In a
nested if construct, you can have an if...elif...else construct inside another if...elif...else construct.
Example:
var = 100
Laboratory Manual
ifvar< 200:
print "Expression value is less than 200"
ifvar == 150:
print "Which is 150"
elifvar == 100:
print "Which is 100"
elifvar == 50:
print "Which is 50"
elifvar< 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"
Laboratory Manual
Topic No. 3
Control Statements
The flow of the programs written in any programming language is sequential by default. Sometimes we may need
to alter the flow of the program. The execution of a specific code may need to be repeated several numbers of
times.
For example, if we need to print the first 10 natural numbers then, instead of using the print statement 10 times,
we can print inside a loop which runs up to 10 iterations. There are the following loop statements in Python.
1. for loop:
The for loop is used in the case where we need to execute some part of the code until the given condition is
satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is
known in advance.
Example:
prime=[2, 3, 7, 5]
for prime in prime:
print(prime)
Output:
2
3
7
5
2. while loop:
The while loop is to be used in the when we don't know the number of iterations in advance. The block of
statements is executed in the while loop until the condition specified in the while loop is satisfied. It is also called
a pre-tested loop.
Example:
# Prints out 0,1,2,3,4
count = 0
while count < 5:
print(count)
count += 1 # This is the same as count = count + 1
Output:
0
1
2
3
4
3. do-while loop:
The do-while loop continues until a given condition satisfies. It is also called post tested loop. It is used when it
is necessary to execute the loop at least once (mostly menu driven programs).
Break Statement:
Laboratory Manual
The break is a keyword in python which is used to bring the program control out of the loop. The break statement
breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to
outer loops. In other words, we can say that break is used to abort the current execution of the program and the
control goes to the next line after the loop.
The break is commonly used in the cases where we need to break the loop for a given condition. The syntax of
the break is given below.
#loop statements
break;
Example:
list =[1,2,3,4]
count = 1;
for i in list:
if i == 4:
print("item matched")
count = count + 1;
break
print("found at", count, "location");
Output:
item matched
found at 2 location
pass Statement:
In Python, the pass keyword is used to execute nothing; it means, when we don't want to execute code, the pass
can be used to execute empty. It just makes the control to pass by without executing any code. If we want to
bypass any code pass statement can be used.
Suppose we have a loop, and we do not want to execute right this moment, but we will execute in the future. Here
we can use the pass.
Example - Pass statement:
# pass is just a placeholder for
# we will add functionality later.
values = {'P', 'y', 't', 'h','o','n'}
for val in values:
pass
Example:
for i in [1,2,3,4,5]:
if(i==4):
pass
print("This is pass block",i)
print(i) Output:
1
2
3
This is pass block 4
4
5
Laboratory Manual
Topic No. 4:
String Manipulation
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes. The
computer does not understand the characters; internally, it stores manipulated character as the combination of the
0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also called
the collection of Unicode characters.
Syntax:
str = "Hi Python !"
Here, if we check the type of the variable str using a Python script
print(type(str)), then it will print a string (str).
In Python, strings are treated as the sequence of characters, which means that Python doesn't support the
character data-type; instead, a single character written as 'p' is treated as the string of length 1.
Operator Description
It is known as concatenation operator used to join the strings given either side of the
+ operator.
It is known as repetition operator. It concatenates the multiple copies of the same
* string.
[] It is known as slice operator. It is used to access the sub-strings of a particular string.
It is known as range slice operator. It is used to access the characters from the
[:] specified range
It is known as membership operator. It returns if a particular sub-string is present in
in the specified string
It is also a membership operator and does the exact reverse of in. It returns true if a
not in particular substring is not present in the specified string.
It is used to specify the raw string. Raw strings are used in the cases where we need to
r/R print the actual meaning of escape characters such as "C://python". To define any
string as a raw string, the character r or R is followed by the string.
It is used to perform string formatting. It makes use of the format specifiers used in C
% programming like %d or %f to map their values in python.
Laboratory Manual
Example:
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Laboratory Manual
Topic No. 5
Lists
A list in Python is used to store the sequence of various types of data. Python lists are mutable type it means we
can modify its element after it is created. However, Python consists of six data-types that are capable to store the
sequences, but the most common and reliable type is the list.
A list can be defined as a collection of values or items of different types. The items in the list are separated with
the comma (,) and enclosed with the square brackets [].
A list can be define as below
L1 = ["John", 102, "USA"]
L2 = [1, 2, 3, 4, 5, 6]
I If we try to print the type of L1, L2, and L3 using type() function then it will come out to be a list.
print(type(L1))
print(type(L2))
Output:
<class 'list'>
<class 'list'>
Characteristics of Lists:
The list has the following characteristics:
• The lists are ordered.
• The element of the list can access by index.
• The lists are the mutable type.
• The lists are mutable types.
• A list can store the number of various elements.
List indexing and splitting:
The indexing is processed in the same way as it happens with the strings. The elements of the list can be accessed
by using the slice operator [].
The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th index, the second
element of the list is stored at the 1st index, and so on.
Laboratory Manual
Fig 1. List Indexing
Unlike other languages, Python provides the flexibility to use the negative indexing also. The negative indices
are counted from the right. The last element (rightmost) of the list has the index -1; its adjacent left element is
present at the index -2 and so on until the left-most elements are encountered.
list Operator:
Operator Description Example
The repetition operator enables the list L1*2 = [1, 2, 3, 4, 1, 2, 3, 4]
Repetition elements to be repeated multiple times.
It concatenates the list mentioned on l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8]
Concatenation either side of the operator.
It returns true if a particular item exists print(2 in l1) prints True.
Membership in a particular list otherwise false.
The for loop is used to iterate over the for i in l1:
list elements. print(i)
Output
Iteration 1
2
3
4
Length It is used to get the length of the list len(l1) = 4
Laboratory Manual
print("HOD Details ....")
print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]))
print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]))
print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT))
Output:
printing employee data...
Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class 'list'><class 'list'><class 'list'><class 'list'><class 'list'>
Laboratory Manual
Topic No. 6:
Tuple
Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar to lists since the
value of the items stored in the list can be changed, whereas the tuple is immutable, and the value of the items
stored in the tuple cannot be changed.
A tuple can be written as the collection of comma-separated (,) values enclosed with the small () brackets. The
parentheses are optional but it is good practice to use. A tuple can be defined as follows.
Example:
T1 = (101, "Peter", 22)
T2 = ("Apple", "Banana", "Orange")
T3 = 10,20,30,40,50
print(type(T1))
print(type(T2))
print(type(T3))
Output:
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
Tuple Indexing:
The indexing and slicing in the tuple are similar to lists. The indexing in the tuple starts from 0 and goes to
length(tuple) - 1.
The items in the tuple can be accessed by using the index [] operator. Python also allows us to use the colon
operator to access multiple items in the tuple.
Consider the following image to understand the indexing and slicing in detail.
Laboratory Manual
Example:
tuple1 = (1, 2, 3, 4, 5)
print(tuple1[-1])
Output
5
Python Tuple Operator:
Operator Description Example
The repetition operator enables the tuple t1*2 = [1, 2, 3, 4, 1, 2, 3,
Repetition elements to be repeated multiple times. 4]
It concatenates the tuple mentioned on either t1+t2 = [1, 2, 3, 4, 5, 6, 7,
Concatenation side of the operator. 8]
It returns true if a particular item exists in a print(2 in t1) prints True.
Membership particular tuple otherwise false.
The for loop is used to iterate over the tuple for i in t1:
Iteration elements. print(i)
Laboratory Manual
Topic No. 7
Set
A Set in Python programming is an unordered collection data type that is mutable and has no duplicate
elements. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for
checking whether a specific element is contained in the set. This is based on a data structure known as a hash
table. Since sets are unordered, we cannot access items using indexes as we do in lists.
Set are represented by { } (values enclosed in curly braces)
Example of Python Sets:
Ex:
Input:
var = {"Geeks", "for", "Geeks"}
type(var)
Output:
set
Type Casting with Python Set method: The Python set() method is used for type casting.
Ex :
Input:
myset = set(["a", "b", "c"])
print(myset)
Output:
{'c', 'b', 'a'}
Python set is an unordered datatype, which means we cannot know in which order the elements of the set are
stored.
Adding element to the set
Ex :
Input:
myset.add("d")
print(myset)
Output:
{'d', 'c', 'b', 'a'}
Check unique and Immutable with Python Set
Python sets cannot have a duplicate value and once it is created we cannot change its value.
Ex :
Input:
# Python program to demonstrate that a set cannot have duplicate values and we cannot change its
items
myset = {"Geeks", "for", "Geeks"}
print(myset)
Laboratory Manual
The second code generates an error because we cannot assign or change a value once the set is
created. We can only add or delete items in the set.
{'Geeks', 'for'}
TypeError: 'set' object does not support item assignment
Laboratory Manual
# Union using union() function
population = people.union(vampires)
print("Union using union() function")
print(population)
# Union using "|" operator
population = people|dracula
print("\nUnion using '|' operator")
print(population)
Output:
Union using union() function
{'Karan', 'Idrish', 'Jay', 'Arjun', 'Archil'}
Union using '|' operator
{'Deepanshu', 'Idrish', 'Jay', 'Raju', 'Archil'}
Intersection operation on Python Sets
This can be done through intersection() or & operator. Common Elements are selected.
Ex :
Input:
# Python program to demonstrate intersection of two sets
set1 = set()
set2 = set()
for i in range(5):
set1.add(i)
for i in range(3,9):
set2.add(i)
# Intersection using intersection() function
set3 = set1.intersection(set2)
print("Intersection using intersection() function")
print(set3)
# Intersection using "&" operator
set3 = set1 & set2
print("\n Intersection using '&' operator")
print(set3)
Output:
Intersection using intersection() function
{3, 4}
Intersection using '&' operator
{3, 4}
Finding Differences of Sets in Python
To find differences between sets. Similar to finding differences in the linked list. This is done through
difference() or – operator.
Ex :
Input:
# Python program to demonstrate difference of two sets
set1 = set()
set2 = set()
for i in range(5):
Laboratory Manual
set1.add(i)
for i in range(3,9):
set2.add(i)
# Difference of two sets using difference() function
set3 = set1.difference(set2)
print(" Difference of two sets using difference() function")
print(set3)
# Difference of two sets using '-' operator
set3 = set1 - set2
print("\nDifference of two sets using '-' operator")
print(set3)
Output:
Difference of two sets using difference() function
{0, 1, 2}
Difference of two sets using '-' operator
{0, 1, 2}
Clearing Python Sets
Set Clear() method empties the whole set in place.
Ex :
Input:
# Python program to demonstrate clearing of set
set1 = {1,2,3,4,5,6}
print("Initial set")
print(set1)
# This method will remove all the elements of the set
set1.clear()
print("\nSet after using clear() function")
print(set1)
Output:
Initial set
{1, 2, 3, 4, 5, 6}
Set after using clear() function
set()
However, there are two major pitfalls in Python sets:
1. The set doesn’t maintain elements in any particular order.
2. Only instances of immutable types can be added to a Python set.
Laboratory Manual
Topic No. 8
Dictionaries
Python Dictionary is used to store the data in a key-value pair format. The dictionary is the data type in Python,
which can simulate the real-life data arrangement where some specific value exists for some particular key. It is
the mutable data-structure. The dictionary is defined into element Keys and values.
• Keys must be a single element
• Value can be any type such as list, tuple, integer, etc.
In other words, we can say that a dictionary is the collection of key-value pairs where the value can be any Python
object. In contrast, the keys are the immutable Python object, i.e., Numbers, string, or tuple.
The dictionary can be created by using multiple key-value pairs enclosed with the curly brackets {}, and each key
is separated from its value by the colon (:). The syntax to define the dictionary is given below:
Syntax:
Dict = {"Name": "Tom", "Age": 22}
In the above dictionary Dict, The keys Name and Age are the string that is an immutable object.
Example:
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"} print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Output:
Dictionary
printing Employee data ....
{‘Name’,: ‘John’, ‘Age’: 29 salary":25000,"Company":"GOOGLE"}
Properties of Dictionary keys:
• In the dictionary, we cannot store multiple values for the same keys. If we pass more than one value for a
single key, then the value which is last assigned is considered as the value of the key.
• In python, the key cannot be any mutable object. We can use numbers, strings, or tuples as the key, but
we cannot use any mutable object like the list as the key in the dictionary.
Laboratory Manual
Output:
Empty Dictionary:
{}
Laboratory Manual
Topic No. 9
Functions
Functions are the most important aspect of an application. A function can be defined as the organized block of
reusable code, which can be called whenever required.
Python allows us to divide a large program into the basic building blocks known as a function. The function
contains the set of programming statements enclosed by {}. A function can be called multiple times to provide
reusability and modularity to the Python program.
Python provide us various inbuilt functions like range() or print(). Although, the user can create its functions,
which can be called user-defined functions. There are mainly two types of functions.
• User-define functions - The user-defined functions are those define by the user to perform the specific
task.
• Built-in functions - The built-in functions are those functions that are pre-defined in Python.
Python provides the def keyword to define the function. The syntax of the define function is given below.
Creating a Function:
Python provides the def keyword to define the function:
• The def keyword, along with the function name is used to define the function.
• The identifier rule must follow the function name.
• A function accepts the parameter (argument), and such parameters can be optional.
• The function block is started with the colon (:), and block statements must be at the same indentation.
• The return statement is used to return the value. A function can have only one return
The syntax of the define function is given below:
Syntax:
def my_function(parameters):
function_block
return expression
Function Calling:
In Python, after the function is created, we can call it from another function. A function must be defined before
the function call; otherwise, the Python interpreter gives an error. To call the function, use the function name
followed by the parentheses.
Example:
#function definition
defhello_world():
print("hello world")
# function calling
hello_world()
Output:
hello world
Python Lambda Functions:
Laboratory Manual
Python Lambda function is known as the anonymous function that is defined without a name. Python allows us
to not declare the function in the standard manner, i.e., by using the def keyword. Rather, the anonymous functions
are declared by using the lambda keyword. However, Lambda functions can accept any number of arguments,
but they can return only one value in the form of expression.
The syntax to define an anonymous function is given below.
Syntax:
lambda arguments: expression
It can accept any number of arguments and has only one expression. It is useful when the function objects are
required.
Example:
# a is an argument and a+10 is an expression which got evaluated and returned.
x = lambda a:a+10
# Here we are printing the function object
print(x)
print("sum = ",x(20))
Output:
<function<lambda> at 0x0000019E285D16A8>
sum = 30
Laboratory Manual
Topic No. 10
Modules
A python module can be defined as a python program file which contains a python code including python
functions, class, or variables. In other words, we can say that our python code file saved with the extension (.py)
is treated as the module. We may have a runnable code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical way. To use the functionality of
one module into another, we must have to import the specific module. We need to load the module in our python
code to use its functionality. Python provides two types of statements as defined below.
1. The import statement
2. The from-import statement
The import statement:
The import statement is used to import all the functionality of one module into another. Here, we must notice that
we can use the functionality of any python source file by importing that file as the module into another python
source file.
We can import multiple modules with a single import statement, but a module is loaded once regardless of the
number of times, it has been imported into our file.
The syntax to use the import statement is given below.
Syntax:
import module1, module2, ........ module n
The from-import statement:
Instead of importing the whole module into the namespace, python provides the flexibility to import only the
specific attributes of a module. This can be done by using from- import statement. The syntax to use the from-
import statement is given below.
Syntax:
from< module-name> import <name 1>, <name 2>..,<name n>
Consider the following module named as calculation which contains three functions as summation,
multiplication, and divide.
calculation.py
#place the code in the calculation.py
def summation(a,b):
return a+b
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;
Main.py:
from calculation import summation
#it will import only the summation() from calculation.py
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
Laboratory Manual
print("Sum = ",summation(a,b)) #we do not need to specify the module name while accessing summation()
Output:
Enter the first number10
Enter the second number20
Sum = 30
The from-import statement is always better to use if we know the attributes to be imported from the module in
advance. It doesn't let our code to be heavier. We can also import all the attributes from a module by using *.
Consider the following syntax.
Syntax:
from<module> import *
TOPIC No. 11
Exception
An exception can be defined as an unusual condition in a program resulting in the interruption in the flow of the
program.
Whenever an exception occurs, the program stops the execution, and thus the further code is not executed.
Therefore, an exception is the run-time errors that are unable to handle to Python script. An exception is a Python
object that represents an error
Python provides a way to handle the exception so that the code can be executed without any interruption. If we
do not handle the exception, the interpreter doesn't execute all the code that exists after the exception.
Some Common Exceptions
Python provides the number of built-in exceptions, but here we are describing the common standard exceptions.
A list of common exceptions that can be thrown from a standard Python program is given below.
• ZeroDivisionError: Occurs when a number is divided by zero
• NameError: It occurs when a name is not found. It may be local or global
• IndentationError: If incorrect indentation is given
• IOError: It occurs when Input Output operation fails
• EOFError: It occurs when the end of the file is reached, and yet operations are being performed
Exception Example:
Suppose we have two variables a and b, which take the input from the user and perform the division of these
values. What if the user entered the zero as the denominator? It will interrupt the program execution and through
a ZeroDivision exception. Let's see the following example.
Example:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d" %c)
Laboratory Manual
#other code:
print("Hi I am other part of the program")
Output:
Enter a:10
Enter b:0
Traceback (most recent call last):
File "exception-test.py", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero
The 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.
except Exception1:
#block of code
except Exception2:
#block of code
#other code
The try...finally block:
Python provides the optional finally statement, which is used with the try statement. It is executed no matter what
exception occurs and used to release the external resource. The finally block provides a guarantee of the execution.
We can use the finally block with the try block in which we can place the necessary code, which must be executed
before the try statement throws an exception.
The syntax to use the finally block is given below.
Laboratory Manual
Syntax:
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
Raising exceptions:
An exception can be raised forcefully by using the raise clause in Python. It is useful in that scenario where we
need to raise an exception to stop the execution of the program.
For example, there is a program that requires 2GB memory for execution, and if the program tries to occupy 2GB
of memory, then we can raise an exception to stop the execution of the program.
The syntax to use the raise statement is given below.
Syntax:
raise Exception_class,<value>
Points to remember:
• To raise an exception, the raise statement is used. The exception class name follows it.
• An exception can be provided with a value that can be given in the parenthesis.
• To access the value "as" keyword is used. "e" is used as a reference variable which stores the value of
the exception.
• We can pass the value to an exception to specify the exception type.
Example:
Laboratory Manual
try:
age = int(input("Enter the age:"))
if(age<18):
raise ValueError
else:
print("the age is valid")
except ValueError:
print("The age is not valid")
Output:
Enter the age:17
The age is not valid
Laboratory Manual
Topic No. 12
Laboratory Manual
Object:
The object is an entity that has state and behavior. It may be any real-world object like the mouse, keyboard,
chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-
in attribute __doc__, which returns the docstring defined in the function source code.
When we define a class, it needs to create an object to allocate the memory. Consider the following example.
Example:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
Output:
Toyota 2016
In the above example, we have created the class named car, and it has two attributes model name and year. We
have created a c1 object to access the class attribute. The c1 object will allocate memory for these values. We will
learn more about class and object in the next tutorial.
Method:
The method is a function that is associated with an object. In Python, a method is not unique to class instances.
Any object type can have methods.
Constructor:
In Python, the method the __init__() simulates the constructor of the class. This method is called when the class
is instantiated. It accepts the self-keyword as a first argument which allows accessing the attributes or method of
the class.
We can pass any number of arguments at the time of creating the class object, depending upon
the __init__() definition. It is mostly used to initialize the class attributes. Every class must have a constructor,
even if it simply relies on the default constructor.
Consider the following example to initialize the Employee class attributes-
Example:
class Employee:
def __init__(self, name, id):
self.id = id
self.name = name
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
emp1 = Employee("John", 101)
emp2 = Employee("David", 102)
Laboratory Manual
# accessing display() method to print employee 1 information
emp1.display()
# accessing display() method to print employee 2 information
emp2.display()
Output:
ID: 101
Name: John
ID: 102
Name: David
Inheritance:
Inheritance is an important aspect of object-oriented programming, which simulates the real-world concept of
inheritance. It specifies that the child object acquires all the properties and behaviors of the parent object.
By using inheritance, we can create a class which uses all the properties and behavior of another class. The new
class is known as a derived class or child class, and the one whose properties are acquired is known as a base
class or parent class. It provides the re-usability of the code.
Laboratory Manual
Animal Speaking
Polymorphism:
Polymorphism contains two words "poly" and "morph". Poly means many, and morph means forms. By
polymorphism, we understand that one task can be performed in different ways. For example - you have a class
animal, and all animals speak. But they speak differently. Here, the "speak" behavior is polymorphic in a sense
and depends on the animal. So, the abstract "animal" concept does not actually "speak", but specific animals (like
dogs and cats) have a concrete implementation of the action "speak".
Encapsulation:
Encapsulation is also an essential aspect of object-oriented programming. It is used to restrict access to methods
and variables. In encapsulation, code and data are wrapped together within a single unit from being modified by
accident.
Data Abstraction:
Data abstraction and encapsulation both are often used as synonyms. Both are nearly synonyms because data
abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities. Abstracting something means to give
names to things so that the name captures the core of what a function or a whole program does.
Example:
class Dog:
defadd_trick(self, trick):
self.tricks.append(trick)
d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll over')
e.add_trick('play dead')
d.tricks
Output:
['roll over', 'play dead']