Professional Documents
Culture Documents
Pyhton Lab Manual IS2132 July-Dec2023
Pyhton Lab Manual IS2132 July-Dec2023
Lab Manual
Python Programming Lab
Course Code: IS 2132
Semester-III
MANIPAL UNIVERSITY JAIPUR
School of Computing and IT
Department of Computer and Communication Engineering
B.Tech Computer Science and Engineering (IoT and Intelligent Systems)
Course Hand-out
Python Programming Lab | IS 2132 | 1 Credits | 0 0 2 1
Ses Session: Aug’23 – Dec’23 | Course Coordinator: Dr. Sourabh Singh Verma | Class: 2nd Year / 3id Sem
Faculty: 1. Dr. Manoj Sharma, 2. Dr. Arpit Sharma
D. Assessment Rubrics:
Criteria Description Maximum
Marks
Internal Assessment (Formative) Fortnightly evaluation 40
(Record + execution + viva)
Mini project 20
End Term Exam (Summative) End Term Exam 40
Total 100
Attendance (Formative) A minimum of 75% Attendance is required to be maintained
by a student to be qualified for taking up the End Semester
examination. The allowance of 25% includes all types of
leaves including medical leaves.
Make up Assignments Students who missed the lab will have to report to the
(Formative) teacher about the absence. A makeup assignment on the
topic taught on the day of absence will be given which has
to be submitted within a week from the date of absence. No
extensions will be given on this. The attendance for that
particular day of absence will be marked blank, so that the
student is not accounted for absence. These assignments are
limited to a maximum of 2 throughout the entire semester.
E. Syllabus
Python IDE: Introduction to Python IDE, Use of Python IDE (Jupyter, Pycharm, Pydev, VIM
etc.). Control Statement: If, If else, else if, nested if, for loop, while loop, do while, break,
continue, pass. Python OOPs: OOPs Concepts, Object, Class, Constructors, Inheritance,
Multilevel Inheritance, Multiple Inheritance. Data structures: List, Set, Dictionary (mapping),
Tuple, Graph (from a third-party library), List Slicing (sub list), List comprehension (shorthand
for a loop), Mutable and immutable data structures, Distinction between identity and (abstract)
value. Functions: Procedural abstraction, Functions as values, recursion, Function design
methodology. The Python Library: String and Text Handling, Data Structures and
Algorithms, Threading, Networking, Web Programming, Graphical Programming, Database
Access. Python GUI: Introduction to python GUI framework, Use of Python GUI.
Reference Books:
1. A. Martelli, Python in a Nutshell, (3e), O'Reilly Media, Inc, 2017.
2. J. Georzen, T. Bower, B. Rhodes, Foundations of Python Network Programming,(3e),
APress, 2014.
3. D. M. Beazley, Python Essential Reference,(4e), Pearson Addison-Wesley Professional,
2009.
4. M. Lutz, Programming Python, (4e), O'Reilly Media, 2010
F. Lecture Plan:
Lect. Topics Session Objective Mode of Corresponding Mode of Assessing the Outcome
No Delivery CO
1 Introduction to Python IDE Make the students familiarized with the development Lab IS2132.1 Internal Evaluation
environment which has been used throughout this Assignments
Course series to run Python code. External Evaluation
Variables, Keywords, Program to demonstrate how to declare Keywords, Lab IS2132.1 Internal Evaluation
Identifiers, Literals, Variables, Datatypes, and Comments in Python. Assignments
Operators, Comments Program to demonstrate different datatypes and External Evaluation
and datatype. arithmetic operations in Python.
2 Data structures: List, Program to create a list and perform various operations Lab IS2132.2 Internal Evaluation
List Slicing and Set on the list. Assignments
Program to demonstrate list slicing in Python External Evaluation
List of Experiments
1. Install Python using Anaconda navigator: Anaconda Navigator is a desktop GUI interface
that comes with Anaconda Individual Edition.
2. Run Python Code on Google Colab: Google provides Jupyter Notebook like interface to
run Python code on online Virtual Machines.
Step 1: Open https://colab.research.google.com/
OUTPUT
Enter first int number: 4
Enter second int number: 5
Sum of integers 4 and 5 is: 9
diff of integers 4 and 5 is: -1
mult of integers 4 and 5 is: 20
Enter first float number: 4.5
Enter second float number: 6.8
Sum of float 4.5 and 6.8 is: 11.3
diff of float 4.5 and 6.8 is: -2.3
mult of float 4.5 and 6.8 is: 30.599999999999998
Enter first complex number: 5+3j
Enter second complex number: 5+2j
Sum of complex (5+3j) and (5+2j) is: (10+5j)
diff of float (5+3j) and (5+2j) is: 1j
mult of float (5+3j) and (5+2j) is: (19+25j)
OUTPUT
Enter amount: 5000
Enter time: 2
Enter rate: 45
Simple interest is : 4500.0
Compound interest is: 5512.5
OUTPUT
The solution are (-3+0j) and (-2+0j)
1.5 WAP in python to swap two variables with and without using temp variable.
# Python program to swap two variables
x=5
y = 10
# To take inputs from the user
#x = input('Enter value of x: ')
#y = input('Enter value of y: ')
# create a temporary variable and swap the values
temp = x
x=y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
OUTPUT
The value of x after swapping: 10
The value of y after swapping: 5
2.Data Structures
2.1 WAP in python to create a list and perform various operations on the list.
Python Lists are like arrays in C. However, the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].
list1 = [1, "hi", "Python", 2]
OUTPUT
[1, 'Manipal', 'University', 2]
[2]
[1, 'Manipal']
[1, 'Manipal', 'University', 2, 1, 'Manipal', 'University', 2]
[1, 'Manipal', 'University', 2, 1, 'Manipal', 'University', 2, 1, 'Manipal', 'University', 2]
2.3 WAP in python to create set and perform various operations on the set
Python Set is the unordered collection of the data type. It is iterable, mutable (can modify after
creation), and has unique elements. In set, the order of the elements is undefined; it may return
the changed sequence of the element.
Source Code
# Creating Empty set
set1 = set()
set2 = {'James', 2, 3,'Python'}
#Printing Set value
print(set2)
# Adding element to the set
set2.add(10)
print(set2)
#Removing element from the set
set2.remove(2)
print(set2)
OUTPUT
{'James', 'Python', 2, 3}
{'Python', 2, 3, 10, 'James'}
{'Python', 3, 10, 'James'}
2.4 WAP in python to create Dictionary and perform various operations on the
dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a
hash table where each key stores a specific value. Key can hold any primitive data type,
whereas value is an arbitrary Python object. The items in the dictionary are separated with the
comma (,) and enclosed in the curly braces {}.
d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
Source Code
d = {1:'Jaipur', 2:'Ajmer', 3:'Jodhpur', 4:'Udaipur'}
# Printing dictionary
print (d)
# Accesing value using keys
print("1st name is "+d[1])
print("2nd name is "+ d[4])
print (d.keys())
print (d.values())
OUTPUT
{1: 'Jaipur', 2: 'Ajmer', 3: 'Jodhpur', 4: 'Udaipur'}
1st name is Jaipur
2nd name is Udaipur
dict_keys([1, 2, 3, 4])
dict_values(['Jaipur', 'Ajmer', 'Jodhpur', 'Udaipur'])
2.5 WAP in python to create Tuple and perform various operations on the Tuple.
A tuple is like the list in many ways. Like lists, tuples also contain the collection of the items of
different data types. The items of the tuple are separated with a comma (,) and enclosed in
parentheses (). A tuple is a read-only data structure as we can't modify the size and value of the
items of a tuple. tup = ("hi", "Python", 2)
Source Code
tup = ("Manipal", "University", 2)
# Checking type of tup
print (type(tup))
#Printing the tuple
print (tup)
# Tuple slicing
print (tup[1:])
print (tup[0:1])
# Tuple concatenation using + operator
print (tup + tup)
# Tuple repatation using * operator
print (tup * 3)
# Adding value to tup. It will throw an error.
tup[2] = "jaipur"
OUTPUT
<class 'tuple'>
('Manipal', 'University', 2)
('University', 2)
('Manipal',)
('Manipal', 'University', 2, 'Manipal', 'University', 2)
('Manipal', 'University', 2, 'Manipal', 'University', 2, 'Manipal', 'University', 2)
TypeError: 'tuple' object does not support item assignment
Source Code
from matplotlib import pyplot as plt
Names = ['Arun','James','Ricky','Patrick']
Marks = [51,87,45,67]
plt.bar(Names,Marks,color = 'blue')
plt.title('Result')
plt.xlabel('Names')
plt.ylabel('Marks')
plt.show()
OUTPUT
3. Control Statements
3.1 WAP in python to check whether a number is even or odd
Source Code
# A number is even if division by 2 gives a remainder of 0.
#If the remainder is 1, it is an odd number
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
OUTPUT
Enter a number: 43
43 is Odd
3.2 WAP in python to find the largest number among the three input numbers
Source Code
# Python program to find the largest number among the three input numbers
# take three numbers from user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
OUTPUT
Enter first number: 10
Enter second number: 12
Enter third number: 14
The largest number is 14.
OUTPUT
Please, Enter the Lowest Range Value: 14
Please, Enter the Upper Range Value: 97
The Prime Numbers in the range are:
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
OUTPUT
Enter a number: 663
663 is not an Armstrong number
3.5 WAP in python to check if a year is a leap year
Source Code
# Python program to check if year is a leap year or not
year = 2000
# To get year (integer input) from the user
# year = int(input("Enter a year: "))
# divided by 100 means century year (ending with 00)
# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
print("{0} is a leap year".format(year))
# not divided by 100 means not a century year
# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
print("{0} is a leap year".format(year))
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))
OUTPUT
2000 is a leap year
OUTPUT
*
**
***
****
*****
Source Code
rows = int(input("Enter number of rows: "))
k=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k=0
print()
OUTPUT
*
***
*****
*******
*********
OUTPUT
The factorial of 7 is 5040
OUTPUT
The sum is 136
OUTPUT
How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8
OUTPUT
s
t
r
The end
print("The end")
OUTPUT
s
t
r
n
g
The end
4. Functions
4.1 WAP in Python to make a Simple Calculator using function
Source Code
# Program make a simple calculator
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
# check if user wants another calculation
# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
OUTPUT
4.2 WAP in python to print LCM and HCF for the given numbers
Source Code (LCM)
def compute_lcm(x, y):
# choose the greater number
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
num1 = 54
num2 = 24
print("The L.C.M. is", compute_lcm(num1, num2))
OUTPUT
The L.C.M. is 216
OUTPUT
The H.C.F. is 6
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
OUTPUT
The factorial of 3 is 6
4.4 WAP in python to print Fibonacci series up to nth term using recursion
Source Code
# Python program to display the Fibonacci sequence
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
OUTPUT
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
5. Object oriented concept
5.1 WAP in python to demonstrate the concept of class and object.
Source Code
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# create a new object of Person class
harry = Person()
# Output: <function Person.greet>
print(Person.greet)
# Output: <bound method Person.greet of < main .Person object>>
print(harry.greet)
# Calling object's greet() method
# Output: Hello
harry.greet()
OUTPUT
<function Person.greet at 0x7fd288e4e160>
<bound method Person.greet of < main .Person object at 0x7fd288e9fa30>>
Hello
OUTPUT
This is our family:
Father : Mark
Mother : Sonia
OUTPUT
This is class A.
This is class B.
This is class C which inherits features of both classes A and B.
Source Code
# Importing math library
import math
A = 16
print(math.sqrt(A))
OUTPUT
4.0
OUTPUT
Socket successfully created
the socket has successfully connected to google
on port == 173.194.40.19
OUTPUT
OUTPUT