Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Python Lab Manual_Harshit Vijayvargiya

This document is a lab manual for a Python programming course, detailing a series of exercises for students to complete. The exercises cover various programming concepts including data types, arithmetic operations, conditionals, loops, strings, lists, tuples, dictionaries, functions, recursion, object-oriented programming, exception handling, and regular expressions. Each exercise includes a brief description and sometimes sample code to guide students in their learning process.

Uploaded by

jacksharma189
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Python Lab Manual_Harshit Vijayvargiya

This document is a lab manual for a Python programming course, detailing a series of exercises for students to complete. The exercises cover various programming concepts including data types, arithmetic operations, conditionals, loops, strings, lists, tuples, dictionaries, functions, recursion, object-oriented programming, exception handling, and regular expressions. Each exercise includes a brief description and sometimes sample code to guide students in their learning process.

Uploaded by

jacksharma189
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

School of Engineering & Technology

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.

a=10; #Integer Datatype


b=11.5; #Float Datatype
c=2.05j; #Complex Number
print("a is Type of",type(a)); #prints type of variable a
print("b is Type of",type(b)); #prints type of variable b
print("c is Type of",type(c)); #prints type of variable c

2. Write a program to perform different Arithmetic Operations on


numbers in Python.

a=int(input("Enter a value")); #input() takes data from console at runtime as string.


b=int(input("Enter b value")); #typecast the input string to int.
print("Addition of a and b ",a+b);
print("Subtraction of a and b ",a-b);
print("Multiplication of a and b ",a*b);
print("Division of a and b ",a/b);
print("Remainder of a and b ",a%b);
print("Exponent of a and b ",a**b); #exponent operator (a^b)
print("Floor division of a and b ",a//b); # floor division

3. Program to create random number generator which generate


random number between 1 and 6
import random
print(random.randint(1, 6)) #Integer from 1 to 6, endpoints included

4. Program to swap two number and display number before


swapping and after swapping

# Take inputs from the user


x = int(input('Enter value of x: '))
y = int(input('Enter value of y: '))
print('The value of x before swapping: {}'.format(x))
print('The value of y before swapping: {}'.format(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))

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

print("\n The Surface area of a Sphere = %.2f" %sa)


print("\n The Volume of a Sphere = %.2f" %Volume)

6. Write a program to check whether an entered year is leap or not.

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))

7. Write a program to find largest among 3 numbers.

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number is", largest)

5
8. Write a Program to check if the entered number is Armstrong or
not.

# take input from the user


num = int(input("Enter a number: "))

# initialize sum
sum = 0

# find the sum of the cube of each digit


temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10

# display the result


if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

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.

roll_num = int(input("Enter your roll number: "))


if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))

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

6
print("Enter Marks Obtained: ")
marks = int(input())

if marks>=80 and marks<=100:


print("Your Grade is Excellent")
elif marks>=65 and marks<80:
print("Your Grade is Good")
elif marks>=50 and marks<65:
print("Your Grade is Pass")
elif marks>=0 and marks<50:
print("Your Grade is Fail")
else:
print("Invalid Input!")

11. Write a python program to find factorial of a number

num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

12. Write a python program that prints prime numbers less than
20.

print("Prime numbers between 1 and 20 are:")


ulmt=20;
for num in range(ulmt):
# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)

7
13. Write a Program to print multiplication table of any number

num = int(input("Display multiplication table of? "))


# Iterate 10 times from i = 1 to 10
for i in range(1, 11):
print(num, 'x', i, '=', num*i)

14. Write a Program to check whether a number is palindrome or


not

num = int(input("Enter a number:"))


temp = num
reverse = 0
while temp > 0:
remainder = temp % 10
reverse = (reverse * 10) + remainder
temp = temp // 10
if num == reverse:
print('Palindrome')
else:
print("Not Palindrome")

15. Write a Program to construct the following pattern using


nested for loop:
*
**
***
****
*****
*****
****
***
**
*

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('')

16. Write a Program to print Fibonacci series up to n terms using


loop statement

nterms = int(input("How many terms? "))


# first two terms
n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

17. Write a program to create, concatenate and print a string and


accessing sub-string from a given string.

s1=input("Enter first String : ");


s2=input("Enter second String : ");
print("First string is : ",s1);
print("Second string is : ",s2);
print("concatenations of two strings :",s1+s2);
print("Substring of given string :",s1[1:4]);

9
18. Write a program find length of a string.

print("Enter the String: ")


text = input()

tot = 0
for ch in text:
tot = tot+1

print("\nLength =", tot)

19. Write a Program to check whether a string is palindrome or


not.

tr_1 = input (“Enter the string to check if it is a palindrome: “)


str_1 = str_1.casefold()
rev_str = reversed (str_1)

if (list str_1) == list (rev_str):


print (“The string is a palindrome.”)
else:
print (“The string is not a palindrome.”)

20. Write a Program to count all letters, digits, and special


symbols from a given string.

string = input("Please Enter your Own String : ")


alphabets = digits = special = 0

for i in range(len(string)):
if(string[i].isalpha()):
alphabets = alphabets + 1
elif(string[i].isdigit()):
digits = digits + 1
else:
special = special + 1

print("\nTotal Number of Alphabets in this String : ", alphabets)


print("Total Number of Digits in this String : ", digits)
print("Total Number of Special Characters in this String : ", special)

10
21. Write a Program to calculate the sum and average of the digits
present in your registration number.

reg = int(input("Enter your registration no:"))


digits = reg[-3:]
n = int(digits)
sum = 0
for num in range(1, n + 1, 1):
sum = sum + num
print("Sum of first ", n, "numbers is: ", sum)
average = sum / n
print("Average of ", n, "numbers is: ", average)

22. Write a program to demonstrate various list operations in


python.

iList = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

# List slicing operations


# printing the complete list
print('iList: ',iList)
# printing first element
print('first element: ',iList[0])
# printing fourth element
print('fourth element: ',iList[3])
# printing list elements from 0th index to 4th index
print('iList elements from 0 to 4 index:',iList[0: 5])
# printing list -7th or 3rd element from the list
print('3rd or -7th element:',iList[-7])

# appending an element to the list


iList.append(111)
print('iList after append():',iList)

# finding index of a specified element


print('index of \'80\': ',iList.index(80))

# sorting the elements of iLIst


iList.sort()
print('after sorting: ', iList);

11
# popping an element
print('Popped elements is: ',iList.pop())
print('after pop(): ', iList);

# removing specified element


iList.remove(80)
print('after removing \'80\': ',iList)

# inserting an element at specified index


# inserting 100 at 2nd index
iList.insert(2, 100)
print('after insert: ', iList)

# counting occurances of a specified element


print('number of occurences of \'100\': ', iList.count(100))

# extending elements i.e. inserting a list to the list


iList.extend([11, 22, 33])
print('after extending:', iList)

#reversing the list


iList.reverse()
print('after reversing:', iList)

23. Write a program to find even numbers from a list

list1 = [10, 21, 4, 45, 66, 93]


# iterating each number in list
for num in list1:
# checking condition
if num % 2 == 0:
print(num, end=" ")

24. Write a program to interchange first and last element of a list

myList = [1, 7, 3, 90, 23, 4]


print("Initial List : ", myList)

# finding the length of list


length = len(myList)

# Swapping first and last element


temp = myList[0]

12
myList[0] = myList[length - 1]
myList[length - 1] = temp

print("List after Swapping : ", myList)

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)

26. Write a program to check all elements are unique or not in


Python

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

a_list = ['aple', 'orange', 'aple', 'banana', 'grape', 'aple']


for i in range(len(a_list)):
if a_list[i] == 'aple':
a_list[i] = 'apple'
print(a_list)

28. Write a program to find the position of minimum and maximum


elements of a list.

list = [10, 1, 2, 20, 3, 20]

# min element's position/index


min = list.index (min(list))
# max element's position/index
max = list.index (max(list))

# printing the position/index of min and max elements


print "position of minimum element: ", min
print "position of maximum element: ", max

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.

#Start with an empty list


data = 0
# Read values, adding them to the list until the user enters 0
nun = int (input (“Enter an integer (0 to quit): "))
while num != 0:
data.append(num)
num = int (input (“Enter an integer (0 to quit): ”))
# Sort the values
data.sort()

#Display the values in ascending order


print("The values sorted into ascending order are:”)
for num in data:
print(num)

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)

#Read the next line of input from the user


line = input ("Enter an integer (blank to quit): ")

#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)

32. Write a program to demonstrate various tuple operations in


python.

t1=(12, 34, 56, 43, 21, 26, 4, 43, 77)


t2=(78, 90)
#Concatenation operator (+)
print(t1+t2)
# Repetition operator (*)
print( t1*3)
# Membership Operator (in, not in)
56 in t1
12 not in t1

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)

33. Write a program to find the size of a tuple

import sys
tup1= ("A", “B”, “C”, 1, 2, 3)
print("Size of tuple: ", sys.getsizeof(tup1), "bytes")

34. Write a program to find the maximum and minimum K


elements in a tuple

myTuple = (4, 9, 1, 7, 3, 6, 5, 2)
K=2

# Finding maximum and minimum k elements in tuple


sortedColl = sorted(list(myTuple))
vals = []
for i in range(K):
vals.append(sortedColl[i])

for i in range((len(sortedColl) - K), len(sortedColl)):


vals.append(sortedColl[i])

print("Tuple : ", str(myTuple))


print("K maximum and minimum values : ", str(vals))

35. Write a program to create a list of tuples from given list having
number and its cube in each tuple

myList = [6, 2, 5 ,1, 4]

# Creating list of tuples


tupleList = []

16
for val in myList:
myTuple = (val, (val*val*val))
tupleList.append(myTuple)

print("The list of Tuples is " , str(tupleList))

36. Write a program to demonstrate working with dictionaries in


python

dict1 = {'StdNo':'532','StuName': 'Naveen', 'StuAge': 21, 'StuCity': 'Hyderabad'}


print("\n Dictionary is :",dict1)
#Accessing specific values
print("\n Student Name is :",dict1['StuName'])
print("\n Student City is :",dict1['StuCity'])
#Display all Keys
print("\n All Keys in Dictionary ")
for x in dict1:
print(x)
#Display all values
print("\n All Values in Dictionary ")
for x in dict1:
print(dict1[x])
#Adding items
dict1["Phno"]=85457854
#Updated dictionary
print("\n Updated Dictionary is :",dict1)
#Change values
dict1["StuName"]="Madhu"
#Updated dictionary
print("\n Uadated Dictionary is :",dict1)
#Removing Items
dict1.pop("StuAge");
#Updated dictionary
print("\n Uadated Dictionary is :",dict1)
#Length of Dictionary
print("Length of Dictionary is :",len(dict1))
#Copy a Dictionary
dict2=dict1.copy()
#New dictionary
print("\n New Dictionary is :",dict2)
#empties the dictionary
dict1.clear()
print("\n Uadated Dictionary is :",dict1)

17
37. Write a Program to create a dictionary from a sequence

test_keys = ["A", "B", "C"]


test_values = [1, 4, 5]
res = {}
for key in test_keys:
for value in test_values:
res[key] = value
test_values.remove(value)
break
print("Resultant dictionary is : ")
print(res)

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 = {}

for i in range(1, n+1):


numbers[i] = i * i

# print dictionary
print(numbers)

39. Write a Program to merge two Python dictionaries into one

dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}


dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

dict3 = dict1.copy()
dict3.update(dict2)
print(dict3)

OR

18
dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

dict3 = {**dict1, **dict2}


print(dict3)

40. 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.

s = input(“Enter a string: “)
characters = { }
for ch in s:
characters[ch] = True

print(“That string contained" , len(characters) , "unique character(s).")

41. Write a Program to write user defined function to swap two


number and display number before swapping and after swapping

def swap(x,y):
print(“Before swapping a :”,x)
print(“Before swapping b :”,y)
x,y=y,x
return x,y

a=int(input(“Enter value : “))


b=int(input(“Enter value : “))
a,b=swap(a,b)
print(“After swapping a becomes :”,a)
print(“After swapping b becomes :”,b)

42. Write a Program to calculate arithmetic operations on two


number using user defined function

def add(n1, n2):


return n1+n2

def minus(n1, n2):


return n1 - n2

def multiply(n1, n2):


return n1 * n2

def divide(n1, n2):

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))

43. Write a Program to Calculate diameter and area of circle using


user defined function

def find_Diameter(radius):
return 2 * radius

def find_Area(radius):
return math.pi * radius * radius

r = float(input(' Please Enter the radius of a circle: '))

diameter = find_Diameter(r)
area = find_Area(r)

print("\n Diameter Of a Circle = %.2f" %diameter)


print(" Area Of a Circle = %.2f" %area)

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.

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))

# Call the main function


main()

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.

from random import randint

SHORTEST = 7
LONGEST = 10
MIN_ASCII = 33
MAX_ASCII = 126

## Generate a random password


# @return a string containing a random password

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

# Return the random password


return result

# Generate and display a random password


def main():
print ("Your random password is:", randomPassword())

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)

# filtering even values using lambda function


evenFibo = list(filter(lambda n:n%2==0,fibo))
print("List of even fibonacci values :",evenFibo)

47. Write a Program to find the sum of elements of a list using


lambda function

from functools import reduce

# List of some fibonacci numbers


fiboList = [0,1,1,2,3,5,8,13,21,34,55]
print("List of fibonacci numbers :", fiboList)

# using Lambda function to add elements of fibonacci list


listSum = reduce(lambda a,b:a+b, fiboList)
print("The sum of all elements is ", listSum)

48. Write a Program to find small number between two numbers


using Lambda function

small = lambda a, b : a if a < b else b

print(small(20, -20))
print(small(10, 8))
print(small(20, 20))

49. Write a python program to find factorial of a number using


Recursion.

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

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))

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): ")

# Base case: The user entered a blank line so the total is 0


if line =="":
return 0
else:
# Recursive case: Convert the current line to a number and use recursion to read the
next line
return float(line) + readAndTotal()

# 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()

# Display the result


print("The total of all those values is", total)

# Call the main function


main()

23
52. Write a Program to implement destructor and constructors
using __del__() and __init__()

class Sample:
num = 0

def __init__(self, var):


Sample.num += 1
self.var = var

print("Object value is = ", var)


print("Variable value = ", Sample.num)

def __del__(self):
Sample.num -= 1

print("Object with value %d is exit from the scope" % self.var)

S1 = Sample(10)

53. Write a Program to implement Getters and Setters in a class

class Employee:
def __init__(self): #Constructor
self.__id = 0
self.__name = ""

def getId(self): #Accessor/Getters


return self.__id
def setId(self,id): #Mutators/Setters
self.__id=id

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()

54. Write a Program to calculate student grade using class

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()

55. Write a Program to illustrate single inheritance in Python

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()

56. Write a Program to illustrate multiple inheritance in Python

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()

57. Write a Program to illustrate multilevel inheritance in Python

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()

58. Write a Program to illustrate hierarchical inheritance in


Python

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()

59. Write a Program to illustrate hybrid inheritance in Python

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"):

class Child3(Parent , Child1):


def func4(self):
print(" this is function 4")

ob = Child3()
ob.func1()

60. Write a Program to illustrate handling of divide by zero


exception

try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))

result = num1 / num2

print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)

61. Write a Program to illustrate handling of IndexError Exception

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)

# Value error if the values is not in range


except ValueError as ex:
print(ex)

# IndexError if the value is out of the list index...


except IndexError as ex:
print(ex)

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 : "))

# Adding the two numbers and printing their result.


numSum = num1 + num2
print("The sum of the two numbers is ",numSum)

# except block
except ValueError as ex:
print(ex)

63. Write a Program to illustrate handling of Type exception

while True:
try:
num = int(input("Enter First Number: "))
print(num)
break
except ValueError as e:
print("Invalid Input..Please Input Integer Only..")

64. Write a Program to match a string that contains only upper


and lowercase letters, numbers, and underscores

import re
def text_match(text):
patterns = '^[a-zA-Z0-9_]*$'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')

print(text_match("The quick brown fox jumps over the lazy dog."))


print(text_match("Python_Exercises_1"))

65. Write a Program that matches a string that has an a followed


by zero or more b's

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"))

66. Write a Program that matches a string that has an a followed


by one or more b's

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"))

69. Write a Program that matches a word at the beginning of a


string

import re
def text_match(text):
patterns = '^\w+'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')

print(text_match("The quick brown fox jumps over the lazy dog."))


print(text_match(" The quick brown fox jumps over the lazy dog."))

70. Write a Program to search some literals strings in a string.

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!')

71. Write a Program to replace whitespaces with an underscore


and vice versa.

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))

73. Write a Program to validate a 10-digit mobile number

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

You might also like