DEPARTMENT OF
COMPUTERSCIENCE
AND ENGINEERING
LAB MANUAL
PYTHON PROGRAMMING LAB
(Year: IV [Link] I- Sem)
(Lab Code: CS751PC)
(Regulation: R16)
PYTHON LAB MANUAL Page 1
[Link] a program to demonstrate different number data types in Python?
Program:
a=5
print(a, "is of type", type(a))
a = 3.1416
print(a, "is of type", type(a)
a = 1+2j
print(a, "is of type", type(a))
a="ssit"
print(a, "is of type", type(a))
list = ["sharath", "sai", "subbu"]
print(list, "is of type", type(list))
tup = ('venkat', 'manoj', 1997, 2000)
print(tup, "is of type", type(tup))
Output:
5 is of type <class 'int'>
3.1416 is of type <class 'float'>
(1+2j) is of type <class 'complex'>
ssit is of type <class 'str'>
['sharath', 'sai', 'subbu'] is of type <class 'list'>
('venkat', 'manoj', 1997, 2000) is of type <class 'tuple'>
PYTHON LAB MANUAL Page 2
[Link] a program to perform different Arithmetic Operations on numbers in Python?
Program:
a=int(input("Enter a value\n"))
b=int(input("Enter b value\n"))
c=int(input("[Link]\[Link]\[Link]\[Link]\[Link]\nchoose your
operation\n"))
if c==1 :
sum=a+b
print("The sum of a and b is ",sum)
elif c==2 :
difference = a-b
print("The difference of a and b is ",difference)
elif c==3 :
product = a*b
print("The product of a and b is ",product)
elif c==4 :
quotient = a/b
print("The quotient of a and b is ",quotient)
elif c==5 :
remainder = a%b
print("The remainder of a and b is ",remainder)
else :
print("Wrong option")
Output:
enter a value
10
enter b value
20
PYTHON LAB MANUAL Page 3
[Link]
[Link]
[Link]
[Link]
[Link]
Choose your operation
The quotient of a and b is 0.5
PYTHON LAB MANUAL Page 4
[Link] a program to create, concatenate and print a string and accessing sub-string from a given
string?
Program:
string1=input("Enter String1\n ")
string2=input("Enter String2\n ")
string3=string1+string2
print("\n String after concatenation=",string3)
print("String1=",string1)
print("String2=",string2)
print("String3=",string3)
print(string1[2:7])
Output:
Enter String1
Fourth
Enter String2
CSE
String after concatenation= FourthCSE
String1= Fourth
String2= CSE
String3= FourthCSE
urth
PYTHON LAB MANUAL Page 5
[Link] a python script to print the current date in the following format “Sun May 29 [Link] IST
2017”?
Program:
import time
import datetime
print("",[Link]().strftime("%A"))
print("",[Link]().strftime("%B"))
print("",[Link]().strftime("%d"))
print("",[Link]())
print("",[Link]().strftime("%Y"))
Output:
Thursday
July
18
2019-07-18 [Link].633980
2019
PYTHON LAB MANUAL Page 6
5. Write a program to create, append, and remove lists in python
Program:
list=[5,2,3]
print(list)
[Link](1)
[Link](4)
print(list)
print(list[3])
[Link](1)
print(list)
list1=["sasi","kumar"]
[Link](list1)
print(list)
Output:
[5, 2,3]
[5, 2,3, 1, 4]
[5, 2,3, 4]
[5, 2,3, 4, ['sasi', 'kumar']]
PYTHON LAB MANUAL Page 7
[Link] a program to demonstrate working with tuples in python
Program:
tuple=("CSE","ECE","EEE","MECH")
print(tuple)
print(tuple[0])
print("the length of the tuple is",len(tuple))
#concatenationof 2 tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ("cse","ssit")
print(tuple1 + tuple2)
# tuple with repetition
tuple3 = ("IVCSE",)*3
print(tuple3)
Output:
('CSE', 'ECE', 'EEE', 'MECH')
CSE
the length of the tuple is 4
(0, 1, 2, 3, 'cse', 'ssit')
('IVCSE', 'IVCSE', 'IVCSE')
PYTHON LAB MANUAL Page 8
[Link] a program to demonstrate working with dictionaries in python?
Program:
Dict={}
print("Empty Dictionary:")
print(Dict)
Dict={1:'cse',2:'in',3:'btech'}
print("\nDIctionary with the use of integers keys")
print(Dict)
Dict={'Name':'cse',1:[1,2,3,4]}
print("\nDictionary with the use of mixed keys")
print(Dict)
Dict=dict([(1,'cse'),(2,'in')])
print("\n Dictionary with each item as a pair")
print(Dict)
Output:
DIctionary with the use of integers keys
{1: 'cse', 2: 'in', 3: 'btech'}
Dictionary with the use of mixed keys
{'Name': 'cse', 1: [1, 2, 3, 4]}
Dictionary with each item as a pair
{1: 'cse', 2: 'in'}
PYTHON LAB MANUAL Page 9
[Link] a python program to find largest of three numbers?
Program:
a=int(input("Enter the first number\n"))
b=int(input("Enter the second number\n"))
c=int(input("Enter the third number\n"))
if (a>=b)and(a>=c):
largest=a
elif (b>=a)and(b>=c):
largest=b
else:
largest=c
print ( "The largest of the three numbers is",largest)
Output:
Enter the first number
Enter the second number
Enter the third number
The largest of the three numbers is 5
PYTHON LAB MANUAL Page 10
[Link] a Python program to convert temperatures to and from Celsius, Fahrenheit. [ Formula: c/5 = f-
32/9]
Program:
def celtofah():
c=float(input("Enter the temperature in celsius\n"))
f=1.8*c+32
print("The temperature in fahrenheit is ",f)
def fahtocel():
f=float(input("Enter the temperature in fahrenheit\n"))
c=0.55*(f-32)
print("The temperature in celsius is ",c)
a=int(input("[Link] to fahrenheit\[Link] to celsius\nchoose your conversion\n"))
if a==1:
celtofah()
elif a==2:
fahtocel()
else :
print("Wrong option")
Output:
[Link] to fahrenheit
[Link] to celsius
choose your conversion
Enter the temperature in celsius
100
The temperature in fahrenheit is 212.0
[Link] to fahrenheit
PYTHON LAB MANUAL Page 11
[Link] to celsius
choose your conversion
Enter the temperature in fahrenheit
98
The temperature in celsius is 36.3
PYTHON LAB MANUAL Page 12
[Link] a Python program to construct the following pattern, using a nested for loop
**
***
****
* * * **
* ***
***
**
Program:
n=5;
for i in range(n):
for j in range(i):
print ('* ', end="")
print('')
for i in range(n,0,-1):
for j in range(i):
print('* ', end="")
print('')
PYTHON LAB MANUAL Page 13
Output:
**
***
****
*****
****
***
**
PYTHON LAB MANUAL Page 14
[Link] a Python script that prints prime numbers less than 20?
Program:
r=20
for a in range(2,r+1):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print(a)
Output:
11
13
17
19
PYTHON LAB MANUAL Page 15
12. Write a python program to find factorial of a number using Recursion?
Program:
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
num = int(input("Enter a number to find its factorial: "))
if num < 0:
print("Sorry, factorial does not exist ")
elif num==0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",factorial(num))
Output:
Enter a number to find its factorial:
The factorial of 7 is 5040
PYTHON LAB MANUAL Page 16
13. Write a program that accepts the lengths of three sides of a triangle as inputs. The program output
should indicate whether or not the triangle is a right triangle (Recall from the Pythagorean Theorem
that in a right triangle, the square of one side equals the sum of the squares of the other two sides).
Program:
a=int(input("Enter the first side length\n"))
b=int(input("Enter the second side length\n"))
c=int(input("Enter the third side length\n"))
if(a>=b)and(a>=c):
largest=a
elif(b>=a)and(b>=c):
largest=b
else:
largest=c
if a==largest and a**2 == b**2+c**2 :
print("The given triangle is a right angled triangle")
elif b==largest and b**2 == a**2+c**2 :
print("The given triangle is a right angled triangle")
elif c==largest and c**2 == a**2+b**2 :
print("The given triangle is a right angled triangle")
else:
print("The given triangle is not a right angled triangle")
PYTHON LAB MANUAL Page 17
Output:
Enter the first side length
Enter the second side length
Enter the third side length
The given triangle is a right angled triangle
PYTHON LAB MANUAL Page 18
14. Write a python program to define a module to find Fibonacci Numbers and import the module to
another program.?
Program:
def fibo(n):
if n <= 1:
return n
else:
return(fibo(n-1) + fibo(n-2))
nterms = int(input("Enter the no of terms\n"))
if nterms <= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(fibo(i))
Output:
Enter the no of terms
10
Fibonacci sequence:
13
21
34
PYTHON LAB MANUAL Page 19
15. Write a python program to define a module and import a specific function in that module to
another program?
Program1:
def fibo(n):
if n <= 1:
return n
else:
return(fibo(n-1) + fibo(n-2))
n=int(input("Enter no of terms\n"))
if n <= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(n):
print(fibo(i))
Program2:
Import fibrecursion
[Link](n)
PYTHON LAB MANUAL Page 20
Output:
Enter no of terms
10
Fibonacci sequence:
13
21
34
PYTHON LAB MANUAL Page 21
16. Write a script named [Link]. This script should prompt the user for the names of two text
files. The contents of the first file should be input and written to the second file.
Program:
import os
from os import path
inputf=input("Enter input file name\n")
if [Link](inputf):
f1=open(inputf,"r")
outputf=input("Enter output file name\n")
f2=open(outputf,"w")
s=[Link]()
[Link](s)
print("File copied Successfully")
[Link]()
[Link]()
else:
print("File does not exist\n")
Output:
Enter input file name
[Link]
Enter output file name
[Link]
File copied Successfully
PYTHON LAB MANUAL Page 22
17. Write a program that inputs a text file. The program should print all of the unique words in the file
in alphabetical order?
Program:
fname=input("Enter the file name\n")
fh=open(fname)
lst=list()
for line in fh:
word=[Link]().split()
for element in word:
if element in lst:
continue
else:
[Link](element)
[Link]()
print(lst)
[Link]:
IV CSE SSIT
Output:
Enter the file name
[Link]
['CSE', 'IV', 'SSIT']
PYTHON LAB MANUAL Page 23
[Link] a Python class to convert an integer to a roman numeral?
Program:
class py_solution:
def Roman(self, num):
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
syb = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I" ]
roman_num=''
i=0
while num > 0:
for _ in range(num // val[i]):
roman_num += syb[i]
num -= val[i]
i += 1
return roman_num
num=int(input("Enter the number\n"))
print("The roman numeral for the given number is ",py_solution().Roman(num))
Output:
Enter the number
54
The roman numeral for the given number is LIV
PYTHON LAB MANUAL Page 24
19. Write a Python class to implement pow(x, n)?
Program:
class py_solution:
def pow(self, x, n):
if x==0 or x==1 or n==1:
return x
if x==-1:
if n%2 ==0:
return 1
else:
return -1
if n==0:
return 1
if n<0:
return 1/[Link](x,-n)
val = [Link](x,n//2)
if n%2 ==0:
return val*val
return val*val*x
x=int(input("Enter the no\n"))
n=int(input("Enter power\n "))
print("the power(x,n)is ",pow(x,n))
Output:
Enter the no
Enter power
the power(x,n)is 125
PYTHON LAB MANUAL Page 25
20. . Write a Python class to reverse a string word by word?
Program:
class py_solution:
def reverse_words(self, s):
return ' '.join(reversed([Link]()))
print(py_solution().reverse_words('IV CSE 2016))
Output:
2016 CSE IV
PYTHON LAB MANUAL Page 26