Python Lab Manual by R.Nakkeeran For JNTUH Python Syllabus
Python Lab Manual by R.Nakkeeran For JNTUH Python Syllabus
Ex. No. : 1
Date:
Algorithm:
Begin
1. A←100
2. b←10.23
3. c←100+3j
4. d←”Hello Python”
5. e←[2,4,6,8]
6. f←("hello", 1,2,3,"go")
7. g← {1:"Jan",2:"Feb", 3:"March"}
8. write type(a)
9. write type(b)
10. write type(c)
11. write type(d)
12. write type(e)
13. write type(f)
14. write type(g)
End
Program:
a=100
b=10.23
c=100+3j
d=”Hello Python”
e=[2,4,6,8]
f=("hello", 1,2,3,"go")
g= {1:"Jan",2:"Feb", 3:"March"}
Output
Result: The program was executed successfully and verified the output
Ex. No. : 2
Date:
Algorithm:
Begin
1. while True
begin
2. write "Operation to perform:"
3. write "1. Addition"
4. write “2. Subtraction"
5. write "3. Multiplication"
6. write "4. Division"
7. write "5. Raising a power to number"
8. write "6. Floor Division”
9. write "7. Modulus or Remainder Division"
10. write "8. Exit"
11. Read choice
12. If choice =='8'
13. stop
14. Read num1
15. Read num2
16. if choice == '1'
17. Write 'Sum of ', num1, "and" ,num2, "=", num1 + num2
18. elif choice == '2'
19. Write 'Difference of ',num1, "and", num2, "=", num1 - num2
20. elif choice == '3'
21. Write 'Multiplication of',num1, "and", num2, "=", num1 * num2
22. elif choice == '4'
23. Write 'Division of',num1, "and", num2, "=", num1 / num2
24. elif choice == '5'
25. Write 'Exponent of ',num1, "**", num2, "=", num1 ** num2
26. elif choice == '6'
27. Write 'Floor Division of ',num1, "//",num2, "=", num1 // num2
28. elif choice == '7'
29. Write 'Modulus of ',num1, "%",num2, "=", num1 % num2
end
End
Program:
while True:
print("\n\n\n");
print("Operation to perform:");
print("1. Addition");
print("2. Subtraction");
print("3. Multiplication");
print("4. Division");
print("5. Raising a power to number");
print("6. Floor Division");
print("7. Modulus or Remainder Division");
print("8. Exit");
choice = input("Enter choice: ");
if choice =='8':
break;
if choice == '1':
print('Sum of ', num1, "and" ,num2, "=", num1 + num2);
Output:
Operation to perform:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Raising a power to number
6. Floor Division
7. Modulus or Remainder Division
8. Exit
Enter choice: 5
Enter first number: 2
Enter second number: 4
Exponent of 2 ** 4 = 16
Operation to perform:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Raising a power to number
6. Floor Division
7. Modulus or Remainder Division
8. Exit
Enter choice: 6
Enter first number: 43
Enter second number: 4
Floor Division of 43 // 4 = 10
Operation to perform:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Raising a power to number
6. Floor Division
Result: The program was executed successfully and verified the output
Ex. No. : 3
Date:
Aim: To write a program to create, concatenate and print a string and accessing sub-string from a
given string.
Algorithm:
Begin
1. s1←'string in single quote'
2. s2←"string in double quote"
3. s3←"""string in triple quote"""
4. s4←'.'
5. s5←'Newsletter'
6. // Printing string
7. write s1
8. write s2
9. write s3
10.s6←s1+s2+s3
11. write "Concatenated string = ",s6
12.Write "Fruits are Apple,Orange,Grape,etc",s4*3
13. //substring or slicing
14.Write "Substring of ",s5," = ",s5[4:7]
15.Write "Substring of ",s5," = ",s5[:4]
16.Write "Substring of ",s5," = ",s5[4:]
17.Write "Substring of ",s5," = ",s5[::2]
18.Write "Substring of ",s5," = ",s5[-6:-1]
19.Write "Substring of ",s5," = ",s5[-6:]
20.Write "Substring of ",s5," = ",s5[-10:-6]
21.Write "Reverse of ",s5," = ",s5[::-1]
End
Program:
# String creation
s1='string in single quote'
s2="string in double quote"
s3="""string in triple quote"""
s4='.'
s5='Newsletter'
# Printing string
print(s1)
print(s2)
print(s3)
#string concatenation
s6=s1+s2+s3
print("Concatenated string = ",s6)
print("Fruits are Apple,Orange,Grape,etc",s4*3)
#substring or slicing
print("Substring of ",s5," = ",s5[4:7])
print("Substring of ",s5," = ",s5[:4])
print("Substring of ",s5," = ",s5[4:])
print("Substring of ",s5," = ",s5[::2])
print("Substring of ",s5," = ",s5[-6:-1])
print("Substring of ",s5," = ",s5[-6:])
print("Substring of ",s5," = ",s5[-10:-6])
print("Reverse of ",s5," = ",s5[::-1])
Output:
string in single quote
string in double quote
Result: The program was executed successfully and verified the output
Ex. No. : 4
Date:
Aim: To write a program to print the current date in the following format “Sun May 29
02:26:23 IST 2017”
Algorithm:
Begin
1. today←datetime.date.today()
2. Write "Today date and time:", today.ctime()
3. Write "Cureent Year: ",datetime.date.today().strftime("%Y")
4. Write "Cureent Year: ",datetime.date.today().strftime("%B")
5. Write "Weakday of the year: ",datetime.date.today().strftime("%w")
6. Write "Day of the month: ",datetime.date.today().strftime("%d")
7. Write "Day of the week: ",datetime.date.today().strftime("%A")
End
Program:
import datetime
import time
today = datetime.date.today()
print("Today date and time:", today.ctime())
print(datetime.datetime.now())
print("Cureent Year: ",datetime.date.today().strftime("%Y"))
print("Cureent Year: ",datetime.date.today().strftime("%B"))
print("Weakday of the year: ",datetime.date.today().strftime("%w"))
Output:
Result: The program was executed successfully and verified the output
Ex. No. : 5
Date:
Algorithm:
Begin
1. lst = []
2. choice←1
3. while choice!=0
begin
4. write "0. Exit"
5. write "1. Add"
6. Write "2. Delete"
7. Write "3. Display"
end
8. Read choice
9. if choice==1
begin
10. Read n
11. lst.append(n)
12. Write "List: ",lst
end
13.elif choice==2
begin
14. if len(lst)==0
begin
17. Read n
18.if n not in lst
begin
19. Write "The item to be removed not in list:"
20. Continue
end
21.lst.remove(n)
22.Write "List: ",lst
23.elif choice==3
24. print("List: ",lst)
25.elif choice==0
26. Write "Exiting!"
27.else:
28.write "Invalid choice!!"
End
Program:
lst = []
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Delete")
print("3. Display")
choice=int(input("Enter choice: "))
if choice==1:
n=int(input("Enter number to append: "))
lst.append(n)
print("List: ",lst)
elif choice==2:
#if lst=[]:
# print("List is empty, no item to remove:")
# continue
if len(lst)==0:
print("List is empty, no item to remove:")
print()
continue
elif choice==3:
print("List: ",lst)
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()
Output:
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 1
Enter number to append: 10
List: [10]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 3
List: [10]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 2
Enter number to remove: 10
List: []
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 2
List is empty, no item to remove:
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 0
Exiting!
Result: The program was executed successfully and verified the output
Ex. No. : 6
Date:
Algorithm:
1. tup1 ←
('jan','feb','mar','apr','may','june','july','august','september','october','november','december' )
2. tup2 ← (1, 2, 3, 4, 5)
3. tup3←(1, "Hello", (11, 22, 33))
4. tup4←('India',[10,20,30],'USA')
5. #print the tuple
6. print(tup1)
7. #iterating in tuple
8. for mon in tup1
9. write mon
10.#accessing the tuple element
11.Write "The element in the 5th position : ",tup1[5]
12.Write tup1[-6]
13. Write "Tuple before addition"
14.Write tup2
15.tup2 = tup2 + (7,)
Program:
tup1 = ('jan','feb','mar','apr','may','june','july','august','september','october','november','december' )
tup2 = (1, 2, 3, 4, 5)
tup3=(1, "Hello", (11, 22, 33))
tup4=('India',[10,20,30],'USA')
#iterating in tuple
for mon in tup1:
print(mon,end=' ')
print()
print(tup2)
tup2 = tup2 + (7,)
print("Tuple after addition")
print(tup2)
tup2=tup2+('apple','orange','banana')
print(tup2)
Output:
('jan', 'feb', 'mar', 'apr', 'may', 'june', 'july', 'august', 'september', 'october', 'november',
'december')
jan feb mar apr may june july august september october november december
The element in the 5th position : june
july
Tuple before addition
(1, 2, 3, 4, 5)
Tuple after addition
(1, 2, 3, 4, 5, 7)
(1, 2, 3, 4, 5, 7, 'apple', 'orange', 'banana')
22
Tuple before change
('India', [10, 20, 30], 'USA')
Tuple after change
('India', [10, 20, 40], 'USA')
Result: The program was executed successfully and verified the output
Ex. No. : 7
Date:
Algorithm:
Begin
1. mon←{1:'jan',2:'feb',3:'mar',4:'apr',5:'may',6:'june'}
2. stud←{'kiran':23,'kumar':20,'dinesh':19,'rakesh':21}
3. write "mon Dictionary is ",str(mon))
4. write "The element in the key position 3 is :",mon[3])
5. write "The mon dictionary values are: ",mon.values())
6. write "The mon dictionary keys are: ",mon.keys())
7. #adding an item in the dictionary
8. write "Before addition"
Program:
mon={1:'jan',2:'feb',3:'mar',4:'apr',5:'may',6:'june'}
stud={'kiran':23,'kumar':20,'dinesh':19,'rakesh':21}
print()
print("Before deletion")
for item in stud.values():
print(item,end=' ')
print()
del stud['kumar']
print("After deletion")
for item in stud.values():
print(item,end=' ')
print("Before change")
print("stud Dictionary is ",str(stud))
stud['dinesh']=55
print("Before change")
print("stud Dictionary is ",str(stud))
Output:
23 20 19 21
After deletion
23 19 21 Before change
stud Dictionary is {'kiran': 23, 'dinesh': 19, 'rakesh': 21}
Before change
stud Dictionary is {'kiran': 23, 'dinesh': 55, 'rakesh': 21}
Key value pair of dictionary
dict_items([('kiran', 23), ('dinesh', 55), ('rakesh', 21)])
Result: The program was executed successfully and verified the output
Ex. No. : 8
Date:
Algorithm:
Begin
1. Read a,b,c
2. big ← a
3. if big<b then
4. big=b
5. If big<c then
6. big=c
7. Write big
End
Program:
big=num1
if (big<num2):
big=num2
if (big<num3):
big=num3
Output:
Enter number 1: 56
Enter number 2: 89
Enter number 3: 5
The Biggest number among the three is : 89.0
Enter number 1: 5
Enter number 2: 80
Enter number 3: 234
The Biggest number among the three is : 234.0
Result: The program was executed successfully and verified the output
Ex. No. : 9
Date:
Algorithm:
1. Read c
2. Read f
3. f← 9/5*c+32
4. Write f
5. c←(f-32)*5/9
6. write c
End
Program:
Output:
Result: The program was executed successfully and verified the output
Ex. No. : 10
Date:
Aim: To Write a Python program to construct the following pattern, using a nested for
loop
Algorithm:
Begin
1. Read n
2. for i ←1 to n+1)
begin
3. for j ← 1 to i+1
4. begin
5. Write "*"
6. end
7. Write (“\n”)
8. end
9. for i←n to 1 step -1
begin
10. for j ←1 to i
begin
11. Write "*"
end
end
End
Program:
for i in range(1,n+1):
for j in range(1,i+1):
print("*",end="")
print()
for i in range(n,1,-1):
for j in range(1,i):
print("*",end="")
print()
Output:
Enter n value : 5
*
**
***
****
*****
****
***
**
*
Enter n value : 8
*
**
***
****
*****
******
*******
********
*******
******
*****
****
***
**
*
Result: The program was executed successfully and verified the output
Ex. No. : 11
Date:
Aim: To write a Python script that prints prime numbers less than n.
Algorithm:
Begin
1. Read r
2. for a in range(2,r+1)
begin
3. k←0
4. for i in range(2,a//2+1)
5. if(a%i==0)
6. k=k+1
7. if(k<=0)
8. Write a
end
End
Program:
Output:
Result: The program was executed successfully and verified the output
Ex. No. : 12
Date:
Algorithm:
Begin
1. Fact(n)
2. Begin
3. if n == 0 or 1 then
4. Return 1;
5. else
6. Return n*Call Fact(n-1);
7. endif
8. End
9. Read n
10.Write “Factorial of “,n,”is = “,Call Fact(n)
End
Program:
def factorial(n):
if n == 1:
return n
else:
return n* factorial(n-1)
Output:
Enter a number: 5
The factorial of 5 is 120
Enter a number: 7
The factorial of 7 is 5040
Result: The program was executed successfully and verified the output
Ex. No. : 13
Date:
Aim: 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
Algorithm:
Begin
1. Read s1,s2,s3
2. big←s1
3. if big<s2 then
4. big←s2
5. If big<s3
6. big←s3
7. if(big==s1) then
8. if(s1**2==(s2**2+s3**2)) then
9. Write "The triangle sides given is a right angled triangle”
10. else
11. Write "The triangle sides given is a not right angled triangle"
12.if(big==s2)
13. if(s2**2==(s1**2+s3**2)) then
14. Write "The triangle sides given is a right angled triangle”
15. else
16. Write "The triangle sides given is a not right angled triangle”
17.if(big==s3) then
18. if(s3**2==(s1**2+s2**2)) then
19. Write "The triangle sides given is a right angled triangle",
20. else:
21. print("The triangle sides given is a not right angled triangle”
End
Program:
big=s1
if(big<s2):
big=s2
if(big<s3):
big=s3
if(big==s1):
if(s1**2==(s2**2+s3**2)):
print("The triangle sides given is a right angled triangle",s1**2,(s2**2+s3**2))
else:
print("The triangle sides given is a not right angled triangle",s1**2,
(s2**2+s3**2))
elif(big==s2):
if(s2**2==(s1**2+s3**2)):
print("The triangle sides given is a right angled triangle",s2**2,(s1**2+s3**2))
else:
print("The triangle sides given is a not right angled triangle", s2**2,
(s1**2+s3**2))
elif(big==s3):
if(s3**2==(s1**2+s2**2)):
print("The triangle sides given is a right angled triangle",s3**2,(s1**2+s2**2))
else:
print("The triangle sides given is a not right angled triangle", s3**2,
(s1**2+s2**2))
Output:
Result: The program was executed successfully and verified the output
Ex. No. : 14
Date:
Aim: To Write a python program to define a module to find Fibonacci Numbers and
import the module to another program.
Algorithm:
Begin
Load module fibo
1.
Read n
2.
Write "The fibonacci series is : "
3.
Call fibo.fib1(n)
4.
Read n
5.
Write "The fibonacci series is : "
6.
Res←Call fibo.fib2(n)
7.
for item in res
begin
8. Write item
end
End
1. function fib1(n)
begin
2. c←0,a←0,b←1
3. while c < n then
begin
4. write a
5. a←b, b←a+b,c←c+1
end
6. function fib2(n)
begin
7. result ← []
8. c←0
9. a←0, b ← 1
10.while c < n then
begin
11. result.append(a)
12. a←b, b←a+b,c← c+1
end
13.return result
Program:
import fibo
while c < n:
result.append(a)
a, b,c = b, a+b,c+1
return result
Output:
Enter n value : 10
The fibonacci series is :
0 1 1 2 3 5 8 13 21 34
Enter n value : 20
The fibonacci series is :
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Result: The program was executed successfully and verified the output
Ex. No. : 15
Date:
Aim: To write a python program to define a module and import a specific function in
that module to another program.
Algorithm:
Begin
from fibo load function fib2
1. Read n
2. Write "The fibonacci series is : "
3. Call fibo.fib1(n)
4. Read n
5. Write "The fibonacci series is : "
6. Res←Call fibo.fib2(n)
7. for item in res
8. begin
9. Write item
end
End
10.function fib1(n)
begin
11. c←0,a←0,b←1
12.while c < n then
begin
13. write a
14. a←b, b←a+b,c←c+1
end
15.function fib2(n)
begin
16. result ← []
17. c←0
18. a←0, b ← 1
19.while c < n then
begin
20. result.append(a)
21. a←b, b←a+b,c← c+1
end
22.return result
Program:
c=0
a, b = 0, 1
while c < n:
result.append(a)
a, b,c = b, a+b,c+1
return result
Output:
Enter n value : 7
The fibonacci series is :
0112358
Result: The program was executed successfully and verified the output
Ex. No. : 16
Date:
Aim: To write a script named copyfile.py. 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.
Algorithm:
Begin
1. Read fn1
2. Read fn2
3. Open fn1 for read mode with file handle fh1
4. Open fn2 for write mode with file handle fh2
5. for line in fh1
begin
6. fh2.write(line)
end
7. close files
End
Program:
fh1=open(f1)
fh2=open(f2,"w")
for line in fh1:
fh2.write(line)
print(line)
fh1.close()
fh2.close()
Output:
Good bye!
Result: The program was executed successfully and verified the output
Ex. No. : 17
Date:
Aim: To write a program that inputs a text file. The program should print all of the
unique words in the file in alphabetical order.
Algorithm
Begin
1. Read fname
2. fh ← open fname for reading
3. lst = list()
4. for line in fh
5. word= line.rstrip().split()
6. for element in word
7. if element in lst then
8. continue
9. else
10. lst.append(element)
11.lst.sort()
12.for item in lst
13. write item
14.sortlst=sorted(lst, key=str.lower)
15.for item in sortlst
16. write item
End
Program:
print()
for item in sortlst:
print(item,end=' ')
Output:
Result: The program was executed successfully and verified the output
Ex. No. : 18
Date:
Algorithm:
Begin
ROMAN_NUMERAL_TABLE ← [
("M", 1000), ("CM", 900), ("D", 500),
("CD", 400), ("C", 100), ("XC", 90),
1. function convert_to_roman(number)
2. begin
3. roman_numerals = []
4. for numeral, value in ROMAN_NUMERAL_TABLE:
5. while value <= number
6. begin
7. number -= value
8. roman_numerals.append(numeral)
9. End
10.return ' '.join(roman_numerals)
11.end
12.Read n
Program:
import sys
ROMAN_NUMERAL_TABLE = [
("M", 1000), ("CM", 900), ("D", 500),
("CD", 400), ("C", 100), ("XC", 90),
("L", 50), ("XL", 40), ("X", 10),
("IX", 9), ("V", 5), ("IV", 4),
("I", 1)
]
def convert_to_roman(number):
roman_numerals = []
for numeral, value in ROMAN_NUMERAL_TABLE:
while value <= number:
number -= value
roman_numerals.append(numeral)
return ''.join(roman_numerals)
Output:
Enter a number: 65
The roman value of 65 is = LXV
Enter a number: 23
The roman value of 23 is = XXIII
Enter a number: 11
The roman value of 11 is = XI
Result: The program was executed successfully and verified the output
Ex. No. : 19
Date:
Algorithm:
Begin
1. class py_solution
2. begin
3. function pow(self, x, n)
4. begin
5. if x==0 or x==1 or n==1 then
6. return x
7. end
8. if x==-1 then
9. if n%2 ==0 then
10. return 1
11.else
12. return -1
13.if n==0 then
14. return 1
15.if n<0 then
16. return 1/call self.pow(x,-n)
17.val = call self.pow(x,n//2)
18.if n%2 ==0 then
19. return val*val
20.return val*val*x
21.while True then
22.begin
23. write "Enter q or Q to quit "
24. Read x
25. Read n
26. if (x=='q' or x=='Q') then
27. break
28. else
29. n=int(n)
30. x=int(x)
31. p=call py_solution().pow(x,n)
32. write x," to the power ",n," is = ",p
33. Continue
34.end
End
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/self.pow(x,-n)
val = self.pow(x,n//2)
if n%2 ==0:
return val*val
return val*val*x
while True:
print("Enter q or Q to quit ")
x=input("Enter x value: ")
n=input("Enter n value: ")
if (x=='q' or x=='Q'):
break
else:
n=int(n)
x=int(x)
p=py_solution().pow(x,n)
print(x," to the power ",n," is = ",p)
print()
continue
Output:
Enter q or Q to quit
Enter x value: 2
Enter n value: 4
2 to the power 4 is = 16
Enter q or Q to quit
Enter x value: 5
Enter n value: 3
5 to the power 3 is = 125
Enter q or Q to quit
Enter x value: 4
Enter n value: -2
4 to the power -2 is = 0.0625
Enter q or Q to quit
Enter x value: 100
Enter n value: 0
100 to the power 0 is = 1
Enter q or Q to quit
Enter x value: q
Enter n value: q
Result: The program was executed successfully and verified the output
Ex. No. : 20
Date:
Algorithm:
Begin
1. class py_solution
2. begin
3. function reverse_words(self, s):
4. return ' '.join(reversed(s.split()))
5. end
6. Read s
7. rs=call py_solution().reverse_words(s)
8. write "The reversed sentence: ",rs
End
Program:
class py_solution:
def reverse_words(self, s):
return ' '.join(reversed(s.split()))
Output:
Result: The program was executed successfully and verified the output