Python lab manual
Python Programming (20CS31P)
Week 1
Python is a widely used high-level programming language. To write
and execute code in python, we first need to install Python on our
system.
Installing Python on Windows takes a series of few easy steps.
Step 1: Download the Full Installer
Follow these steps to download the full installer:
• Open a browser window and navigate to the Python.org
Downloads
page for Windows.
• Under the “Python Releases for Windows” heading, click the link
for the Latest Python 3 Release - Python 3.x.x. As of this writing, the
latest version was Python 3.10.
• Scroll to the bottom and select either Windows x86-64 executable
installer for 64-bit or Windows x86 executable installer for 32-bit.
Step 2 − Run Executable Installer
We downloaded the Python 3.10 Windows 64 bit installer.
Run the installer. Make sure to select both the checkboxes at the
bottom and then click Install New.
On clicking the Install Now, The installation process starts.
The installation process will take few minutes to complete and once
the
installation is successful, the following screen is displayed.
Step 3 − Verify Python is installed on Windows
To ensure if Python is successfully installed on your system. Follow
the given steps
• Open the command prompt.
• Type ‘python’ and press enter.
The version of the python which you have installed will be displayed
if the python is successfully installed on your windows.
PyCharm is a cross-platform editor developed by JetBrains. Pycharm
provides all the tools you need for productive Python development.
Below are the detailed steps for installing PyCharm
Step1: To download PyCharm visit the website
https://www.jetbrains.com/pycharm/download/ and Click the
“DOWNLOAD” link under the Community Section.
Step 2): Once the download is complete, run the exe for install
PyCharm. The setup wizard should have started. Click “Next”.
Step 3): On the next screen, Change the installation path if required.
Click “Next”.
Step 4): On the next screen, you can create a desktop shortcut if you
want and click on “Next”.
Step 5): Choose the start menu folder. Keep selected JetBrains and
click
on “Install”.
Step 6): Wait for the installation to finish.
Step 7): Once installation finished, you should receive a message
screen that PyCharm is installed. If you want to go ahead and run it,
click the “Run PyCharm Community Edition” box first and click
“Finish”.
Step 8): After you click on “Finish,” the Following screen will appear.
Week -2
2 a . write a python program to perform Arithmetic operations and
display formatted output.
num1 = input(’Enter first number: ‘)
num2 = input(’Enter second number: ‘)
sum = float(num1) + float(num2)
min = float(num1) - float(num2)
mul = float(num1) * float(num2)
div = float(num1) / float(num2)
mod = float(num1) % float(num2)
expo = float(num1) ** float(num2)
print(’The sum of {0} and {1} is {2}’.format(num1, num2, sum))
print(’The subtraction of {0} and {1} is {2}’.format(num1, num2, min))
print(’The multiplication of {0} and {1} is {2}’.format(num1, num2,
mul))
print(’The division of {0} and {1} is {2}’.format(num1, num2, div))
print(’The module of {0} and {1} is {2}’.format(num1, num2, mod))
print(’The exponent of {0} and {1} is {2}’.format(num1, num2, expo))
Algorithm: step1: start
Step 2: Read the value for num1,num2,
Step 3 :(find addition, subtraction,
multiplication,division,modules and exponential)
Step 4 : sum = num1 + num2
min = num1 - num2
mul = num1 * num2
div = num1 / num2
mod = num1 % num2
expo = num1 ** num2
Step4: print min,sum,mul,div,mod,expo
Step 5: stop
2 b . Write a python program to find average of three numbers.
num1 = float(input(”ENTER first number: “))
num2 = float(input(”ENTER second number: “))
num3 = float(input(”Enter third number:”’’))
avg = (num1+num2+num3)/3
print(”the average of numbers=”, avg)
Algorithm: step1: start
Step 2: Read the value for num1,num2,num3
Step 3 : (find the average of three numbers)
Average <- (num1+num2+num3)/3
Step 4 : print Average
Step 5 : stop
2 C. write a python program to evaluate the following expression
and display formatted output.
i) (X+Y)^2 = X^2 + Y^2 + 2XY
ii) (a+b+c)^2 = a^2 + b^2 + c^2 + 2ab +2bc +2ca
x,y = 4,3
a,b,c = 1,2,3
rest1 = x*x+y*y+2*x*y
print(”({}+{})^2={}”. format(x,y,rest1))
rest2 = a*a+b*b+c*c+2*a*b+2*b*c+2*c*a
print(”({}+{}+{})^2={}”. format(a,b,c,rest2))
Algorithm : step 1: read the value x,y and a,b,c
Step 2: [evaluate the expression]
rest1 = x*x+y*y+2*x*y
rest2 = a*a+b*b+c*c+2*a*b+2*b*c+2*c*a
Step 3: print the result
WEEK -3
3. Identify and Code, execute and debug programs using
conditional statements.
3 a) Write a program to check the given number is positive or
negative number?
n = int(input(”enter a number: “))
if n>0:
print(”positive”)
elif n<0:
print(”negative”)
else:
print(”not in range”)
Algorithm: step 1 : start
Step2 : Read the value n
Step 3: if(n>0) goto step4
elif(n<0) goto step5
else (n = 0) goto step 6
step4: print positive
Step5: print negative
Step 6 : print not in range
Steep 7 : stop
3. b)Write a program to find out grades of students?
marks=int(input(”enter student a marks: “))
if marks > 75:
print(”distinction”)
elif marks > 60:
print(”First class”)
elif marks > 40:
print(”second class”)
elif marks < 35:
print(” fail”)
else:
print(” just pass”)
Algorithm: step 1 : start
Step2 : Read the student marks
Step 3: if marks > 75 goto step4
elif marks >60 goto step 5
elif marks >40 goto step 6
elif marks <35 goto step 7 otherwise goto step 8
step4: print distinction
Step5: print first class
Step 6 : print second class
Step 7 : print fail
Step8: print just pass
Step 9: stop
WEEK 4
4 a) Write a program to print “hello” 5 times using while loop?
n=1
while n<=5:
n = n+1
print(”hello”)
Algorithm: step1: start
Step 2: declare while loop variable n
Step 3: initialise n
Step 4: print “hello”
Step 5: increment n by 1
n <-- n+1
Step 6: if n<5 then go to step4
Step 7: display the result
Step 8: stop
4.b)Write a program to add sum of n natural numbers using for in
range()?
sum=0
for i in range(1,11):
sum=sum+i
print(”sum of n natural numbers:”, sum)
Algorithm: step1: start
Step 2: declare variable as sum
Step 3: sum of n natural numbers using for in range
for i in range (1,11)
Step 4: sum =sum+1
Step 5: print “sum of n natural numbers”,sum
Step 6: display sum
Step 7: stop
4 c ) Write a program to illustrate a break and continue?
for val in “hello”:
if val==”l”:
break
print(val)
print(”the end”)
for val in “hello”:
if val==”l”:
continue
print(val)
print(”the end”)
Algorithm: step1: start
Step 2: if the loop condition is true,it will execute step2 , where in the
body of the loop will get executed.
Step 3: if the loop’s body has break statement the loop will exit and
go to step5
Step 4: if the loop’s body has a continue statement,the statement is
true,it continue the process.
Step5 : stop
WEEK 5
5a . Write a python program to perform fallowing
operation on set.
i) Union
(ii) Difference
(iii) Symmetric Difference
(iv) Intersection.
set1={10,20,30,40,50}
set2={30,40,50,60,70}
print(set1.intersection(set2))
print(set1.union(set2))
print(set1.difference(set2))
print(set1.symmetric_difference(set2))
Algorithm: step 1: start
Step2: declare variable as set1 and set2
Step3: assign value to the variable
Step4: do functions to print a set1 and set2 by using
the intersection, union, difference , isdisjoint,
symmetric_difference.
Step5:display the result
Step6:stop
5 b. Write a python program to access tuple elements
using indexing and slice operator
tuple = (1,2,3,4,5,6,7)
print(tuple[0])
print(tuple[1])
print(tuple[2])
print(”elements from first to end”)
print(tuple[1:])
print(”element 0 to 3”)
print(tuple[:4])
print(”element 1 to 4”)
print(tuple[1:5])
print(”element 0 to 6 and take step 2”)
print(tuple[0:6:2])
print(”elements using negative indexing”)
print(tuple[-1])
print(tuple[-4])
print(tuple[-3:-1])
Algorithm: step 1: start
Step 2: declare variable as tuple
Step 3: insert a value in tuple
Step4: print(tuple[0])
print(tuple[1])
print(tuple[2])
print(tuple[1:])
print(tuple[:4])
print(tuple[1:5])
print(tuple[0:6:2])
print(tuple[-1])
print(tuple[-4])
print(tuple[-3:-1])
Step5: display the result
Step6: stop
WEEK 6
6 a ) Write a python program to perform following
operations on list
i) Concatenate two list
ii) Copy a list to newlist
iii) Find max and min element of list
iv) Sort the elements of list
v) Reverse the elements of list
list1 = [2, 3, 4,7,0]
list2 = [4, 5, 6]
print(”after concatenating two lis”)
list3 = list1 + list2
print(list3)
print(”copying list to new list”)
newlist = list1.copy()
print(newlist)
print(”after sorting elements”)
list1.sort()
print(list1)
print(”after reversing list elements”)
list1.reverse()
print(list1)
print(”min and max element of list1”)
print(max(list1))
print(min(list2))
Algorithm:
Step1: start
Step 2: create a list list1 and list2
Step3:list3 = list1 + list2
print(list3)
newlist = list1.copy()
print(newlist)
list1.sort()
print(list1)
list1.reverse()
print(list1)
print(max(list1))
print(min(list2))
Step5: display the result
Step6: stop
6 b)Write a program to increasing a value of integer
power of 2 using list comprehension?
pow2=[2**x for x in range(10)]
print(pow2)
Algorithm: step 1: start
Step 2: declare variable as pow2
Step 3: insert a value (2**x for x in range(10)) in pow2
variable
Step4: print(pow2)
Step5: display the result
Step6: stop
WEEK 7
7 a) Write a python program to perform following
operations
a) get the values of dictionary
b) get the keys of dictionary
c) add the element to dictionary
d) delete the element from dictionary
car = {”brand”: “Ford”,”model”: “Mustang”,”year”:
1964}
print(”values of dictionary”)
x = car.values()
print(x)
print(”keys of dictionary”)
y=car.keys()
print(y)
print(”after adding element to dictionary”)
car[”color”] = “red”
print(x)
print(”after removing last element”)
car.popitem()
print(car)
Algorithm:
Step1: start
Step 2: create dictionary car
car = {”brand”: “Ford”,”model”: “Mustang”,”year”:
1964}
Step3 : perform the operation
x = car.values()
print(x)
y=car.keys()
print(y)
car[”color”] = “red”
print(x)
car.popitem()
print(car)
Step4: stop
7 b) Write a python program to find even elements of
dictionary using comprehension
squares = {x:x*x for x in range (6)}
print(squares)
squares = { }
for x in range(6):
squares[x] = x*x
print(squares)
Algorithm: step 1: start
Step 2: declare variable as squares
Step 3: insert a {x:x*x for x in range} in squares
Using flower braces dictionary
Step4: print(squares)
Step5: display the result
Step6: stop
WEEK 8
8a. Write a python program to perform following
operations on array
a) Insert element at particular position
b) Delete a specified element
c) Get the index of particular element
from array import *
array1 = array(’i’, [10,20,30,40,50])
print (array1[0])
print (array1[2])
print(”after inserting element”)
array1.insert(1,60)
print(array1)
print(”after deleting element 40”)
array1.remove(40)
print(array1)
print(”element 50 present at “)
print(array1.index(50))
print(”after deleting 3rd element”)
array1.pop(2)
print(array1)
Algorithm:
Step1:start
Step2: import array module
Step3: create a array with integer data
array1 = array(’i’, [10,20,30,40,50])
Step4: print (array1[0])
print (array1[2])
Step5: inserting element to the array
array1.insert(1,60)
print(array1)
Step6: removeing element from array
array1.remove(40)
print(array1)
Step7: searching element from array
print(array1.index(50))
Step8: deleting 3rd element from array
array1.pop(2)
print(array1)
Step9:stop
8. b) Write a python program perform following
operation string
a) Get the characters from 2 to position 5
b) Convert given string to uppercase
c) Convert the given string to lower case
d) Replace the character with specified one
e) Split the string to substring
b = “Hello, World!”
print(”characters from position 2 to position 5”)
print(b[2:5])
print(”to uppercase”)
print(b.upper())
print(”to lower case”)
print(b.lower())
print(”after replacing H with j”)
print(b.replace(”H”, “J”))
print(”split the string to sub string”)
print(b.split(”,”))
Algorithm:
Step1: start
Step2: create a string
b = “Hello, World!”
Ste3:print(b[2:5])
step4:print(b.upper())
Step5: print(b.lower())
Step6:print(b.replace(”H”, “J”))
step7: print(b.split(”,”))
Step8: stop
WEEK 9
9a Write a python program to perform following
using built-in functions
a)convert given to binary
b)find the pow of given number
c)find the absolute value of given number
x = bool(1)
print(x)
x = bin(36)
print(x)
x = pow(4, 3)
print(x)
x = abs(-7.25)
print(x)
Algorithm:
Step1: start
Step2: declare a variable x
Step3: x = bool(1) goto step4
x = bin(36) goto step4
x = pow(4, 3) goto step4
x = abs(-7.25) goto step4
Step4: print(x)
Step5: stop
9 b. Write a python program to find factorial of given
number using function
def factorial(num):
fact=1
while(num!=0):
fact=fact*num
num=num-1
print(”facorial is”,fact)
num=int(input(”enter the number “))
factorial(num)
Algorithm:
Step1:read the input num
Step2:call the function factorial(num)
Step3: def factorial(num)
fact=1
while(num!=0) if condition fails goto step4
find fact=fact*num
num=num-1
Step4: then print(fact)
9 C. Write a program to multiple of two values using
lambda function?
r=lambda x,y : x*y
print(r(12,3))
Algorithm step1 : start
Step2 : Read a variable r
Step3 : assign the value to variable r
r = lambda x,y:x*y
Step4 : print(r(12,3))
Step5: display the result
Step6 : stop
WEEK -10
10 a. Write a python program to perform following
using built-in modules
a) Find square root of number
b) Factorial of given number
c) Find the addition of two numbers
d) Check whether first number greater than second
or not
e) Find mod of two numbers
from math import *
from operator import *
print(sqrt(16))
print(factorial(5))
a, b = 10, 20
print(mul(a, b))
print(gt(a, b))
print(mod(a, b))
Algorithm:
Step1:start
Step2: import math module and operator module
Step3: declare a variables a,b
Step4: print(sqrt(16))
Step 5: print(factorial(5))
Step 6: print(mul(a, b))
Step 7: print(gt(a, b))
Step 8: print(mod(a, b))
Step 9: stop
10.b) Write a python program to print emojis faces?
print(”\U0001f600” “-Grinning Face”)
print(”\U0001F917””-Hugging Face”)
print(”\U0001F923””-Rolling on the floor laughing”)
print(”\U0001f601” “-Hushed Face”)
print(”\U0001F610””-Neutral Face”)
print(”\U0001F924””-Crying Face”)
Algorithm step1 : start
Step2 :Write some unicode of emojis
Step3 : print(”\U0001f600”)
print(”\U0001F917”)
print(”\U0001F923”)
print(”\U0001f601”)
print(”\U0001F61”)
print(”\U0001F924”)
Step4: display the result
Step5: stop
WEEK - 11
11. a)Write a program to perform given below NumPy
operations
i) Subtraction
ii)division
iii)multiplication
iv)square root
import numpy as np
a=[1,3,4]
b=[4,5,6]
print(np.subtract(a,b))
print(np.divide(a,b))
print(np.multiply(a,b))
print(np.sqrt(a))
Algorithm: Step1: start
Step2: convert a numpy as np,
import numpy as np
Step3: declare two variables are a,b
Step4: insert a values to variable a,b
Step5: print(np.subtract(a,b))
print(np.devide(a,b))
print(np.multiply(a,b))
print(np.sqr(a,b))
Step6: display the result
Step 7: stop
11. b)Write a program to find minimum and
maximum number of array ?
import numpy as np
a=np.array([1,3,9,2,7])
print(np.min(a))
print(np.max(a))
Algorithm: Step1: start
Step2: convert a numpy as np,
import numpy as np
Step3: declare a. variables are a
Step4: insert a values to variable a
Step5: print(np.min(a,b))
print(np.max(a,b))
Step6: display the result
Step 7: stop
11c) Create a dataframe from a dictionary ?
import pandas as pd
dict1={’fruit’:[’apple’,’mango’,’banana’],’count’:
[10,12,13]}
df=pd.DataFrame(dict1)
print(df)
Algorithm: Step1: start
Step2: convert a pandas as pd
import pandas as pd
Step3: declare a variables are dict1 and df
Indict1 insert a fruit name & count
& In df = pd.data frame(dict1)
Step4: print(df)
Step5: display the result
Step6: stop
WEEK -12
12. a) Write a program to read first 5 characters from
a files?
f=open(“test.txt”,”r”)
print(f.read(5))
Algorithm: step1 : start
Step2: declare one variable is f
Step 3: insert in f
f = open(”text.text”,”r”)
Step 4: print (f.read)
Step5: display the result
Step6: stop
12. b)Write a program to read file using for loop
statement?
f=open(“test.txt”,”r”)
for x in f:
print(x)
Algorithm: step1 : start
Step2: declare one variable is f
Step 3: insert in f
f = open(”text.text”,”r”)
Step 4: for x in f:
Step5: print(x)
Step6: display the result
Step7: stop
WEEK 13
13 a. Write a python code to integrate exception
handling
try:
f = open(”demo.txt”)
try:
f.write(”Hello everyone”)
except:
print(”Something went wrong when writing to the
file”)
finally:
f.close()
except:
print(”Something went wrong when opening the file”)
Algorithm: step1: start
Step2: use try function
try:
f=open (”demo.txt”)
try:
F.write(”Hello everyone”)
Step3 : use except function
Except
Step4: print(”Something went wrong when writing to
the file”)
Step4:use finally function
finally:
f.close()
Step5: use except function
Except
Step6: print(”Something went wrong when opening
the file”)
Step7: display the result
Step 8: stop
13.b) Program to depict Raising Exception
try:
raise NameError(”Hi there”)
except NameError:
print (”An exception”)
raise
Algorithm: step1: start
Step2: use try function
try:
Rise name error(”Hi there”)
Step3 : use except function
Except name error
Step4:print(”an exception”)
Rise
Step5: display the result
Step 6: stop