Python Lab Manual_Harshit Vijayvargiya
Python Lab Manual_Harshit Vijayvargiya
LAB MANUAL
(BCO 082A)
PROGRAMMING WITH PYTHON LAB
IV Semester
B. Tech. (CSE)
Harshit Vijayvargiya
LIST OF LAB EXERCISES
A 1. Write a program to demonstrate different number data types in Python.
Basic 2. Write a program to perform different Arithmetic Operations on numbers
in Python.
3. Program to create random number generator which generate random
number between 1 and 6
4. Program to swap two number and display number before swapping and
after swapping
5. Write a program in python, that calculates the volume of a sphere with
radius r entered by the user. (Assume π = 3.14)
B 6. Write a program to check whether an entered year is leap or not.
Conditional 7. Write a program to find largest among 3 numbers.
Statements 8. Write a Program to check if the entered number is Armstrong or not.
9. Write a program that reads roll no. from a student. Then your program
should display a message indicating whether the number is even or odd.
10. Let us say a teacher decided to give grades to her students as follows:
a) Mark greater than or equal to 80: Excellent
b) Mark greater than or equal to 65 but less than 80: Good
c) Mark greater than or equal to 50 but less than 65: Pass
d) Mark less than 50: Fail
Write a program in python to print a grade according to a student's mark
with multiple if statements
C 11. Write a python program to find factorial of a number
Loops 12. Write a python program that prints prime numbers less than 20.
13. Write a Program to print multiplication table of any number
14. Write a Program to check whether a number is palindrome or not
15. Write a Program to construct the following pattern using nested for loop:
*
**
***
****
***
**
*
16. Write a Program to print Fibonacci series up to n terms using loop
statement
D 17. Write a program to create, concatenate and print a string and accessing
String sub-string from a given string.
18. Write a program find length of a string.
19. Write a Program to check whether a string is palindrome or not.
20. Write a Program to count all letters, digits, and special symbols from a
given string.
21. Write a Program to calculate the sum and average of the digits present in
your registration number.
E 22. Write a program to demonstrate various list operations in python.
Lists 23. Write a program to find even numbers from a list
24. Write a program to interchange first and last element of a list
25. Write a program to turn every item of a list into its square
26. Write a program to check all elements are unique or not in Python
1
27. Write a program to replace list’s item with new value if found
28. Write a program to find the position of minimum and maximum elements
of a list.
29. Write a program to find the cumulative sum of elements of a list
30. Write a program that reads integers from the user and stores them in a
list. Your program should continue reading values until the user enters 0.
Then it should display all of the values entered by the user (except for the
0) in order from smallest to largest, with one value appearing on each line.
31. Write a program that reads integers from the user until a blank line is
entered. Once all of the integers have been read your program should
display all of the negative numbers, followed by all of the zeros, followed
by all of the positive numbers. Within each group the numbers should be
displayed in the same order that they were entered by the user. For
example, if the user enters the values 3, -4, 1, 0, -1, 0, and -2 then your
program should output the values -4, -1, -2, 0, 0, 3, and 1.
F 32. Write a program to demonstrate various tuple operations in python.
Tuples 33. Write a program to find the size of a tuple
34. Write a program to find the maximum and minimum K elements in a tuple
35. Write a program to create a list of tuples from given list having number
and its cube in each tuple
G 36. Write a program to demonstrate working with dictionaries in python
Dictionary 37. Write a Program to create a dictionary from a sequence
38. Write a Program to generate dictionary of numbers and their squares (i,
i*i) from 1 to N
39. Write a Program that determines and displays the number of unique
characters in a string entered by the user. For example, “Hello, World!”
has 10 unique characters while “zzz” has only one unique character. Use
a dictionary to solve this problem.
40. Two words are anagrams if they contain all of the same letters, but in a
different order. For example, “evil” and “live” are anagrams because each
contains one ‘e’, one ‘I’, one ‘l’, and one ‘v’. Create a program that reads
two strings from the user, determines whether or not they are anagrams,
and reports the result.
H 41. Write a Program to write user defined function to swap two number and
Functions display number before swapping and after swapping
42. Write a Program to calculate arithmetic operation on two number using
user defined function
43. Write a Program to Calculate diameter and area of circle using user
defined function
44. Write a function that takes three numbers as parameters, and returns the
median value of those parameters as its result. Include a main program
that reads three values from the user and displays their median.
45. Write a function that generates a random password. The password should
have a random length of between 7 and 10 characters. Each character
should be randomly selected from positions 33 to 126 in the ASCII table.
Your function will not take any parameters. It will return the randomly
generated password as its only result.
46. Write a Program to filter even values from list using lambda function
47. Write a Program to find the sum of elements of a list using lambda
function
2
48. Write a Program to find small number between two numbers using
Lambda function
I 49. Write a python program to find factorial of a number using Recursion.
Recursion 50. Write a Program to print Fibonacci series up to n terms using recursion
51. Write a program that reads values from the user until a blank line is
entered. Display the total of all of the values entered by the user (or 0.0
if the first value entered is a blank line). Complete this task using
recursion. Your program may not use any loops.
J 52. Write a Program to implement destructor and constructors using
OOP __del__() and __init__()
53. Write a Program to implement Getters and Setters in a class
54. Write a Program to calculate student grade using class
55. Write a Program to illustrate single inheritance in Python
56. Write a Program to illustrate multiple inheritance in Python
57. Write a Program to illustrate multilevel inheritance in Python
58. Write a Program to illustrate heirarchical inheritance in Python
59. Write a Program to illustrate hybrid inheritance in Python
K 60. Write a Program to illustrate handling of divide by zero exception
Exception 61. Write a Program to illustrate handling of IndexError Exception
Handling 62. Write a Program to illustrate handling of ValueError Exception
63. Write a Program to illustrate handling of Type exception
L 64. Write a Program to match a string that contains only upper and lowercase
Regular letters, numbers, and underscores
Expression 65. Write a Program that matches a string that has an a followed by zero or
more b's
66. Write a Program that matches a string that has an a followed by one or
more b's
67. Write a Program that matches a string that has an a followed by three 'b'
68. Write a Program to find the sequences of one upper case letter followed
by lower case letters
69. Write a Program that matches a word at the beginning of a string
70. Write a Program to search some literals strings in a string.
71. Write a Program to replace whitespaces with an underscore and vice
versa.
72. Write a Program to remove all whitespaces from a string.
73. Write a Program to validate a 10-digit mobile number
3
1. Write a program to demonstrate different number data types in
Python.
4
5. Write a program in python, that calculates the volume and
surface area of a sphere with radius r entered by the user.
(Assume π = 3.14)
PI = 3.14
radius = float(input('Please Enter the Radius of a Sphere: '))
sa = 4 * PI * radius * radius
Volume = (4 / 3) * PI * radius * radius * radius
# 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))
5
8. Write a Program to check if the entered number is Armstrong or
not.
# initialize sum
sum = 0
9. Write a program that reads roll no. from a student. Then your
program should display a message indicating whether the
number is even or odd.
6
print("Enter Marks Obtained: ")
marks = int(input())
factorial = 1
12. Write a python program that prints prime numbers less than
20.
7
13. Write a Program to print multiplication table of any number
n=5;
for i in range(n):
for j in range(i):
print ('* ', end="")
print('')
8
for i in range(n,0,-1):
for j in range(i):
print('* ', end="")
print('')
9
18. Write a program find length of a string.
tot = 0
for ch in text:
tot = tot+1
for i in range(len(string)):
if(string[i].isalpha()):
alphabets = alphabets + 1
elif(string[i].isdigit()):
digits = digits + 1
else:
special = special + 1
10
21. Write a Program to calculate the sum and average of the digits
present in your registration number.
iList = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
11
# popping an element
print('Popped elements is: ',iList.pop())
print('after pop(): ', iList);
12
myList[0] = myList[length - 1]
myList[length - 1] = temp
25. Write a program to turn every item of a list into its square
numbers = [1, 2, 3, 4, 5]
squared_numbers = [number ** 2 for number in numbers]
print(squared_numbers)
Alist = ['Mon','Tue','Wed','Mon']
print("The given list : ",Alist)
# Compare length for unique elements
if(len(set(Alist)) == len(Alist)):
print("All elements are unique.")
else:
print("All elements are not unique.")
27. Write a program to replace list’s item with new value if found
13
29. Write a program to find the cumulative sum of elements of a
list
list=[10,20,30,40,50]
new_list=[]
j=0
for i in range(0,len(list)):
j+=list[i]
new_list.append(j)
print(new_list)
30. Write a program that reads integers from the user and stores
them in a list. Your program should continue reading values until
the user enters 0. Then it should display all of the values entered
by the user (except for the 0) in order from smallest to largest,
with one value appearing on each line.
31. Write a program that reads integers from the user until a blank
line is entered. Once all of the integers have been read your
program should display all of the negative numbers, followed by
all of the zeros, followed by all of the positive numbers. Within
each group the numbers should be displayed in the same order
that they were entered by the user. For example, if the user
14
enters the values 3, -4, 1, 0, -1, 0, and -2 then your program should
output the values -4, -1, -2, 0, 0, 3, and 1.
#Create three lists to store the negative, zero and positive values
negatives = []
zeros = []
positives = []
#Read all of the integers from the user, storing each integer in the correct list
line = input ("Enter an integer (blank to quit): ")
while line != "":
num = int (line)
if num < 0:
negatives.append(num)
elif num > 0:
positives.append(num)
else:
zeros.append(num)
#Display all of the negative values, then all of the zeros, then all of the positive values
print (“The numbers were: “)
for n in negatives:
print(n)
for n in zeros:
print(n)
for n in positives:
print(n)
15
#Tuple Functions
print(max(t1))
print(min(t1))
print(any(t1))
print(all(t1))
sorted(t1)
t1.index(56)
t1.count(43)
list1=[12,34,56]
t3= tuple( list1)
print(t3)
import sys
tup1= ("A", “B”, “C”, 1, 2, 3)
print("Size of tuple: ", sys.getsizeof(tup1), "bytes")
myTuple = (4, 9, 1, 7, 3, 6, 5, 2)
K=2
35. Write a program to create a list of tuples from given list having
number and its cube in each tuple
16
for val in myList:
myTuple = (val, (val*val*val))
tupleList.append(myTuple)
17
37. Write a Program to create a dictionary from a sequence
OR
index = [1, 2, 3]
languages = ['python', 'c', 'c++']
dictionary = dict(zip(index, languages))
print(dictionary)
38. Write a Program to generate dictionary of numbers and their
squares (i, i*i) from 1 to N
n = 10
numbers = {}
# print dictionary
print(numbers)
dict3 = dict1.copy()
dict3.update(dict2)
print(dict3)
OR
18
dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
s = input(“Enter a string: “)
characters = { }
for ch in s:
characters[ch] = True
def swap(x,y):
print(“Before swapping a :”,x)
print(“Before swapping b :”,y)
x,y=y,x
return x,y
19
return n1 / n2
num1= int(input("Enter First number :"))
num2 = int(input("Enter Second number :"))
print("+++++++++Addition +++++++++++++")
print(num1,"+" ,num2,"=", add(num1,num2))
print("--------------Substraction-----------")
print(num1,"-" ,num2,"=", minus(num1, num2))
print("***************Multiplication************")
print(num1,"*" ,num2,"=",multiply(num1, num2))
print("///////////////Division//////////////////")
print(num1,"/", num2,"=",divide(num1, num2))
def find_Diameter(radius):
return 2 * radius
def find_Area(radius):
return math.pi * radius * radius
diameter = find_Diameter(r)
area = find_Area(r)
def median(a,b,c):
if a > b:
if a < c:
return a
elif b > c:
return b
else:
return c
else:
if a > c:
return a
elif b < c:
return b
else:
return c
20
def main():
x = float(input("Enter the first value: "))
y = float(input("Enter the second value: "))
z = float (input ("Enter the third value: "))
print ("The median value is:", median(x, y, z))
SHORTEST = 7
LONGEST = 10
MIN_ASCII = 33
MAX_ASCII = 126
def randomPassword():
# Select a random length for the password
randomLength = randint (SHORTEST, LONGEST)
# Generate an appropriate no. of random chars, adding each one to the end of result
result = ""
for i in range(randomLength):
randomChar = chr(randint (MIN_ASCII, MAX_ASCII))
result = result + randomChar
main()
21
46. Write a Program to filter even values from list using lambda
function
fibo = [0,1,1,2,3,5,8,13,21,34,55]
print("List of fibonacci values :",fibo)
print(small(20, -20))
print(small(10, 8))
print(small(20, 20))
def factorial(num):
if num < 0:
print("Invalid number...")
elif num == 0 or num == 1:
return 1
else:
return num * factorial(num - 1)
# main code
x = int(input("Enter an integer number: "))
print("Factorial of ", x, " is = ", factorial(x))
22
50. Write a Program to print Fibonacci series up to n terms using
recursion
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10
51. Write a program that reads values from the user until a blank
line is entered. Display the total of all of the values entered by
the user (or 0.0 if the first value entered is a blank line). Complete
this task using recursion. Your program may not use any loops.
def readAndTotal():
# Read a value from the user
line = input("Enter a number (blank to quit): ")
# Read a collection of numbers from the user and display the total
def main():
# Read the values from the user and compute the total
total = readAndTotal()
23
52. Write a Program to implement destructor and constructors
using __del__() and __init__()
class Sample:
num = 0
def __del__(self):
Sample.num -= 1
S1 = Sample(10)
class Employee:
def __init__(self): #Constructor
self.__id = 0
self.__name = ""
def getName(self):
return self.__name
def setName(self,name):
self.__name=name
def main():
print("Enter Employee Data:")
id = int(input("Enter Id\t:"))
name = input("Enter Name\t:")
e=Employee()
e.setId(id)
e.setName(name)
id2 = e.getId()
name2 = e.getName()
24
print("\nDisplaying Employee Data:")
print("Id\t\t:", id2)
print("Name\t:", name2)
if __name__=="__main__":
main()
class Student:
def __init__(self):
self.__roll=0
self.__name=""
self.__marks=[]
self.__total=0
self.__per=0
self.__grade=""
self.__result=""
def setStudent(self):
self.__roll=int(input("Enter Roll: "))
self.__name=input("Enter Name: ")
print("Enter marks of 5 subjects: ")
for i in range(5):
self.__marks.append(int(input("Subject "+str(i+1)+": ")))
def calculateTotal(self):
for x in self.__marks:
self.__total+=x
def calculatePercentage(self):
self.__per=self.__total/5
def calculateGrade(self):
if self.__per>=85:
self.__grade="S"
elif self.__per>=75:
self.__grade="A"
elif self.__per>=65:
self.__grade="B"
elif self.__per>=55:
self.__grade="C"
elif self.__per>=50:
self.__grade="D"
else:
self.__grade="F"
def calculateResult(self):
25
count=0
for x in self.__marks:
if x>=50:
count+=1
if count==5:
self.__result="PASS"
elif count>=3:
self.__result="COMP."
else:
self.__result="FAIL"
def showStudent(self):
self.calculateTotal()
self.calculatePercentage()
self.calculateGrade()
self.calculateResult()
print(self.__roll,"\t\t",self.__name,"\t\t",self.__total,"\t\t",self.__per,"\t\t",self.__grade,"
\t\t",self.__result)
def main():
#Student object
s=Student()
s.setStudent()
s.showStudent()
if __name__=="__main__":
main()
class Parent:
def func1(self):
print("this is function one")
class Child(Parent):
def func2(self):
print(" this is function 2 ")
ob = Child()
ob.func1()
ob.func2()
class Parent:
def func1(self):
print("this is function 1")
class Parent2:
def func2(self):
print("this is function 2")
26
class Child(Parent , Parent2):
def func3(self):
print("this is function 3")
ob = Child()
ob.func1()
ob.func2()
ob.func3()
class Parent:
def func1(self):
print("this is function 1")
class Child(Parent):
def func2(self):
print("this is function 2")
class Child2(Child):
def func3("this is function 3")
ob = Child2()
ob.func1()
ob.func2()
ob.func3()
class Parent:
def func1(self):
print("this is function 1")
class Child(Parent):
def func2(self):
print("this is function 2")
class Child2(Parent):
def func3(self):
print("this is function 3")
ob = Child()
ob1 = Child2()
ob.func1()
ob.func2()
class Parent:
def func1(self):
print("this is function one")
27
class Child(Parent):
def func2(self):
print("this is function 2")
class Child1(Parent):
def func3(self):
print(" this is function 3"):
ob = Child3()
ob.func1()
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)
try:
employees = ["pankaj","amit","dilip","pooja","nitisha"]
id = int(input("Enter Id (1-5):"))
print("Your name is ",employees[id-1]," and your id is ",id)
28
62. Write a Program to illustrate handling of ValueError Exception
try:
# Taking input from the user ...
# The input strictly needs to be an integer value...
num1 = int(input("Enter number 1 : "))
num2 = int(input("Enter number 2 : "))
# except block
except ValueError as ex:
print(ex)
while True:
try:
num = int(input("Enter First Number: "))
print(num)
break
except ValueError as e:
print("Invalid Input..Please Input Integer Only..")
import re
def text_match(text):
patterns = '^[a-zA-Z0-9_]*$'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
import re
def text_match(text):
patterns = '^a(b*)$'
29
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(text_match("ac"))
print(text_match("abc"))
print(text_match("a"))
print(text_match("ab"))
print(text_match("abb"))
import re
def text_match(text):
patterns = 'ab+?'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(text_match("ab"))
print(text_match("abc"))
67. Write a Program that matches a string that has an 'a' followed
by three 'b'
import re
def text_match(text):
patterns = 'ab{3}?'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(text_match("abbb"))
print(text_match("aabbbbbc"))
68. Write a Program to find the sequences of one upper case letter
followed by lower case letters
import re
def text_match(text):
patterns = '[A-Z]+[a-z]+$'
if re.search(patterns, text):
return 'Found a match!'
30
else:
return('Not matched!')
print(text_match("AaBbGg"))
print(text_match("Python"))
print(text_match("python"))
print(text_match("PYTHON"))
print(text_match("aA"))
print(text_match("Aa"))
import re
def text_match(text):
patterns = '^\w+'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
import re
patterns = [ 'fox', 'dog', 'horse' ]
text = 'The quick brown fox jumps over the lazy dog.'
for pattern in patterns:
print('Searching for "%s" in "%s" ->' % (pattern, text),)
if re.search(pattern, text):
print('Matched!')
else:
print('Not Matched!')
import re
text = 'Python Exercises'
text =text.replace (" ", "_")
print(text)
text =text.replace ("_", " ")
print(text)
31
72. Write a Program to remove all whitespaces from a string.
import re
text1 = ' Python Exercises '
print("Original string:",text1)
print("Without extra spaces:",re.sub(r'\s+', '',text1))
import re
n=input('Enter Mobile number :')
r=re.fullmatch('[6-9][0-9]{9}',n)
if r!=None:
print('Valid Number')
else:
print('Not a valid number')
32