0% found this document useful (0 votes)
1 views19 pages

Python Lab Mannual

The document provides a comprehensive introduction to Python programming, including multiple programs that demonstrate various concepts such as reading user input, calculating marks and percentages, generating Fibonacci sequences, and handling exceptions. It also covers advanced topics like creating classes and functions for complex numbers, calculating binomial coefficients, and file handling. Additionally, it includes a set of viva questions related to Python programming concepts.

Uploaded by

arjunsom339
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views19 pages

Python Lab Mannual

The document provides a comprehensive introduction to Python programming, including multiple programs that demonstrate various concepts such as reading user input, calculating marks and percentages, generating Fibonacci sequences, and handling exceptions. It also covers advanced topics like creating classes and functions for complex numbers, calculating binomial coefficients, and file handling. Additionally, it includes a set of viva questions related to Python programming concepts.

Uploaded by

arjunsom339
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to Python Programming Language-BPCLK105B/205B

PROGRAM – 1(a). Develop a program to read the student details like Name, USN, and Marks in three
subjects. Display the student details, total marks and percentage with suitable messages.
print("enter the student name")
name =input()
print("enter your USN")
USN=input()
print("enter your physics marks")
p=int(input())
print("enter your chemistry marks")
c=int(input())
print("enter your maths marks")
m=int(input())
Total=p+c+m
Percentage=(Total/300)*100
print("The student details are")
print("student name is",name)
print("student USN is", USN)
print("physics marks is",p)
print("chemistry marks is",c)
print("maths marks is",m)
print("the total marks obtained is", Total)
print("the percentile obtained is ",Percentage)
print("ALL THE BEST")
Output:
enter the student name
Max
enter your USN
1JT20CS001
enter your physics marks
95
enter your chemistry marks
96
enter your maths marks
100
The student details are
student name is Max

Department of Computer Science & Engineering, JIT – Bangalore. Page 1


Introduction to Python Programming Language-BPCLK105B/205B

student USN is 1JT20CS001


physics marks is 95
chemistry marks is 96
maths marks is 100
the total marks obtained is 291
the percentile obtained is 97.0
ALL THE BEST

Department of Computer Science & Engineering, JIT – Bangalore. Page 2


Introduction to Python Programming Language-BPCLK105B/205B

PROGRAM – 1 (b) Develop a program to read the name and year of birth of a person. Display whether
the person is a senior citizen or not.
print("Enter your name")
name=input()
print("Enter your year of birth")
year_of_birth=int(input())
print("Enter present year ")
present_year=int(input())
age=present_year- year_of_birth
print("Your Age is",age)
if age>60:
print("You are a senior citizen")
else:
print("You are not a senior citizen")

Output:
Enter your name
Jonny
Enter your year of birth
2002
Enter present year
2025
Your Age is 23
You are not a senior citizen

Department of Computer Science & Engineering, JIT – Bangalore. Page 3


Introduction to Python Programming Language-BPCLK105B/205B

PROGRAM – 2 (a). Develop a program to generate Fibonacci sequence of length (N). Read N from the
console.
print ("Enter the length of Fibonacci Series")
n=int(input())
n1=0
n2=1
print ("Fibonacci Series for the length",n,"is as follows")
print(n1)
print(n2)
for x in range(2,n):
n3=n1+n2
print (n3)
n1=n2
n2=n3
Output:
Enter the length of Fibonacci Series
10
Fibonacci Series for the length 10 is as follows
0
1
1
2
3
5
8
13
21
34

Department of Computer Science & Engineering, JIT – Bangalore. Page 4


Introduction to Python Programming Language-BPCLK105B/205B

PROGRAM - 2 (b). Write a function to calculate factorial of a number. Develop a program to compute
binomial coefficient (Given N and R).
def fact(num):
fact=1
for i in range (num,0,-1):
fact=fact*i
return fact
N=int (input("Enter the value for N"))
R=int (input("Enter the value for R"))
NF=fact(N)
RF=fact(R)
print("Factorial of ",N,"is", NF)
NRF=fact(N-R)
BMC=NF/(RF*(NRF))
print ("Binomial co efficient is", BMC)

Output:
Enter the value for N = 8

Enter the value for R = 5

Factorial of 8 is 40320

Binomial co efficient is 56.0

Department of Computer Science & Engineering, JIT – Bangalore. Page 5


Introduction to Python Programming Language-BPCLK105B/205B

PROGRAM - 3. Read N numbers from the console and create a list. Develop a program to print mean,
variance and standard deviation with suitable messages.
import math

def mean(data):
n = len(data)
mean = sum(data) / n
return mean

def variance(data):
n = len(data)
mean_value = sum(data) / n
deviation = ((x - mean_value) ** 2 for x in data)
variance = sum(deviation) / n
return variance

def stddev(data):
var = variance(data)
stddev = [Link](var)
return stddev

n = []
while True:
print(f"To stop, press -1\nEnter the number {len(n)}:")
num = int(input())
if num == -1:
break
n = n + [num]
print(n)
print("Mean:", mean(n))
print("Variance:", variance(n))
print("Standard Deviation:", stddev(n))

Department of Computer Science & Engineering, JIT – Bangalore. Page 6


Introduction to Python Programming Language-BPCLK105B/205B

Output:
To stop, press -1
Enter the number 0:
5
[5]
Mean: 5.0
Variance: 0.0
Standard Deviation: 0.0
To stop, press -1
Enter the number 1:
3
[5, 3]
Mean: 4.0
Variance: 1.0
Standard Deviation: 1.0
To stop, press -1
Enter the number 2:
8
[5, 3, 8]
Mean: 5.333333333333333
Variance: 4.222222222222222
Standard Deviation: 2.053741123964354
To stop, press -1
Enter the number 3:
-1

Department of Computer Science & Engineering, JIT – Bangalore. Page 7


Introduction to Python Programming Language-BPCLK105B/205B

PROGRAM - 4. Read a multi-digit number (as chars) from the console. Develop a program to print the
frequency of each digit with suitable message.

number = input("Enter the number\n")


count = {}
L1 = []
for character in number:
if character not in L1:
[Link](character)
[Link](character, 0)
count[character] += 1
print("The frequency of digits is as follows:")
print(L1)
for x in L1:
print(x, '-', [Link](x), 'times')
Output:
Enter the number

112233

The frequency of digits is as follows:

['1', '2', '3']

1 - 2 times

2 - 2 times

3 - 2 times

Department of Computer Science & Engineering, JIT – Bangalore. Page 8


Introduction to Python Programming Language-BPCLK105B/205B

PROGRAM - 5. Develop a program to print 10 most frequently appearing words in a text file. [Hint: Use
dictionary with distinct words and their frequency of occurrences. Sort the dictionary in the reverse
order of frequency and display dictionary slice of first 10 items]
import pprint
myfile = open("C:\\Users\\STUDENT\\Desktop\\[Link]", 'r')
c = [Link]()
[Link]()
type(c)
cl = [Link]()
freq = {}
for c1 in cl:
if c1 in freq:
freq[c1] = freq[c1] + 1
else:
freq[c1] = 1
fl = {}
print("frequency of words of 10 most repeating words")
for n, f in [Link]():
fl[n] = f
fsorted = sorted([Link](), key=lambda x: x[1])
[Link]()
fn = fsorted[0:10]
print([Link](fn) )
Output:
apple banana apple orange banana apple grape orange banana apple

Frequency of words of 10 most repeating words:

[('apple', 4),

('banana', 3),

('orange', 2),

('grape', 1)]

Department of Computer Science & Engineering, JIT – Bangalore. Page 9


Introduction to Python Programming Language-BPCLK105B/205B

PROGRAM - 6. Develop a program to sort the contents of a text file and write the sorted contents into a
separate textfile. [Hint: Use string methods strip(), len(), list methods sort(), append(), and file methods
open(), readlines(), and write()].
file = open("C:\\Users\\STUDENT\\Desktop\\[Link]")
s = [Link]()
[Link]()
split_file = [Link]()
sorted_f = sorted(split_file)
file2 = open("C:\\Users\\STUDENT\\Desktop\\[Link]", 'w')
for x in sorted_f:
[Link](f'{x}\n')
print('done')
[Link]()

Output:
banana apple orange grape apple

apple
apple
banana
grape
orange

Department of Computer Science & Engineering, JIT – Bangalore. Page 10


Introduction to Python Programming Language-BPCLK105B/205B

PROGRAM - 7. Develop a program to backing up a given Folder (Folder in a current working directory)
into a ZIP File by using relevant modules and suitable methods.
import zipfile
[Link]('[Link]','w')
[Link]("C:\\Users\\Student\\Desktop\\[Link]",compress_type=zipfile.ZIP_DEFLATED) print("done")
[Link]()
file=[Link]('[Link]')
print([Link]())
[Link]('D:\W')
[Link]()

Output:

Department of Computer Science & Engineering, JIT – Bangalore. Page 11


Introduction to Python Programming Language-BPCLK105B/205B

PROGRAM - 8. Write a function named DivExp which takes TWO parameters a, b and returns a value c
(c=a/b). Write suitable assertion for a>0 in function DivExp and raise an exception for when b=0.
Develop a suitable program which reads two values from the console and calls a function DivExp.
def DivExp(a, b):
assert a > 0, "the a is less than 0"
if b == 0:
raise Exception('b should not be equal to 0')
c=a/b
return c

try:
print('Enter the a value')
a = int(input())
print('Enter the b value')
b = int(input())
print(DivExp(a, b))
except Exception as err:
print(err)
Output:

Case 1 :
Enter the a value
10
Enter the b value
2
5.0

Case 2: (a<=0)

Enter the a value


-5
Enter the b value
2
the a is less than 0

Department of Computer Science & Engineering, JIT – Bangalore. Page 12


Introduction to Python Programming Language-BPCLK105B/205B

Case 3: b==0

Enter the a value


10
Enter the b value
0
b should not be equal to 0

Department of Computer Science & Engineering, JIT – Bangalore. Page 13


Introduction to Python Programming Language-BPCLK105B/205B

PROGRAM - 9. Define a function which takes TWO objects representing complex numbers and returns
new complex number with a addition of two complex numbers. Define a suitable class 'Complex' to
represent the complex number. Develop a program to read N (N>=2) complex numbers and to compute
the addition of N complex numbers.

class Complex:
def __init__(self, tempReal, tempImaginary):
[Link] = tempReal
[Link] = tempImaginary

def addComp(self, c1, c2):


temp = Complex(0, 0)
[Link] = [Link] + [Link]
[Link] = [Link] + [Link]
return temp

if __name__ == '__main__':
print("Enter the complex number 1 real and imaginary part:")
a = int(input())
b = int(input())
c1 = Complex(a, b)
print("Complex number 1:", [Link], "+i" + str([Link]))

print("\nEnter the complex number 2 real and imaginary:")


c = int(input())
d = int(input())
c2 = Complex(c, d)
print("Complex number 2:", [Link], "+i" + str([Link]))

c3 = Complex(0, 0)
c3 = [Link](c1, c2)
print("\nSum of complex numbers:", [Link], "+i" + str([Link]))

Department of Computer Science & Engineering, JIT – Bangalore. Page 14


Introduction to Python Programming Language-BPCLK105B/205B

Output:
Enter the complex number 1 real and imaginary part:
2
3

Enter the complex number 2 real and imaginary:


4
5

Complex number 1: 2 +i3

Enter the complex number 2 real and imaginary:


4
5

Complex number 2: 4 +i5

Sum of complex numbers: 6 +i8

Enter the complex number 1 real and imaginary part:


2
3

Complex number 1: 2 +i3

Enter the complex number 2 real and imaginary:


4
5

Complex number 2: 4 +i5

Sum of complex numbers: 6 +i8

Department of Computer Science & Engineering, JIT – Bangalore. Page 15


Introduction to Python Programming Language-BPCLK105B/205B

PROGRAM - 10. Develop a program that uses class Student which prompts the user to enter marks in
three subjects and calculates total marks, percentage and displays the score card details. [Hint: Use list to
store the marks in three subjects and total marks. Use_init() method to initialize name, USN and the lists
to store marks and total, Use getMarks() method to read marks into the list, and display() method to
display the score card details.]

class Student:
def __init__(self, name, usn):
[Link] = name
[Link] = usn
[Link] = []
def get_marks(self):
for x in range(3):
m = int(input('Enter the marks: '))
[Link](m)
def display(self):
print('\nStudent name:', [Link])
print('Student USN:', [Link])
for x in range(3):
print(f'Marks in sub{x+1}: {[Link][x]}')
def total_marks(self):
self.total_m = sum([Link])
[Link] = (self.total_m / 300) * 100
print('Total marks:', self.total_m)
print('Percentage obtained:', [Link])
n = input('Enter the name of the student: ')
usn = input('Enter the student USN: ')
p = Student(n, usn)
p.get_marks()
[Link]()
p.total_marks()

Department of Computer Science & Engineering, JIT – Bangalore. Page 16


Introduction to Python Programming Language-BPCLK105B/205B

Output:
Enter the name of the student: John Doe
Enter the student USN: 12345
Enter the marks: 85
Enter the marks: 90
Enter the marks: 88

Student name: John Doe


Student USN: 12345
Marks in sub1: 85
Marks in sub2: 90
Marks in sub3: 88
Total marks: 263
Percentage obtained: 87.66666666666667

Department of Computer Science & Engineering, JIT – Bangalore. Page 17


Introduction to Python Programming Language-BPCLK105B/205B

Viva Question
Q 1. What is Python? List some popular applications of Python in the world of technology.

Q 2. What are the benefits of using Python language as a tool in the present scenario?

Q 3. Is Python a compiled language or an interpreted language?

Q 4. Describe the Python Functions?

Q 5. What is the difference between a Mutable datatype and an Immutable data type?

Q 6. What is zip() capability in Python?

Q 7. How are arguments passed by value or by reference in Python?

Q 8. How is Exceptional handling done in Python?

Q 9. Can we Pass a function as an argument in Python?

Q 10. What is swapcase() function in the Python?

Q 11. What is Scope in Python?

Q 12. What is docstring in Python?

Q 13. What is tuple in Python?

Q 14. What are the different file processing modes supported by Python?

Q 15. What are the different types of operators in Python?

Q 16. What is a break, continue, and pass in Python?

Q 17. What are iterators in Python?

Q 18. What is the difference between xrange and range functions?

Q 19. is Python interpreted language?

Q 20. What is the difference between a shallow copy and a deep copy?

Q 21. Which sorting technique is used by sort() and sorted() functions of python?

Q 22. How is memory management done in Python?

Q 23. What is slicing in Python?

Department of Computer Science & Engineering, JIT – Bangalore. Page 18


Introduction to Python Programming Language-BPCLK105B/205B

Q 24. What are Access Specifiers in Python?

Q 25. What is a negative index in Python and why are they used?

Q 26. Python Global Interpreter Lock (GIL)?

Q 27. What are Function Annotations in Python?

Q 28. What is the usage of help() and dir() function in Python?

Q 29. How Python does Compile-time and Run-time code checking?

Q 30. What is the usage of enumerate () function in Python?

Department of Computer Science & Engineering, JIT – Bangalore. Page 19

You might also like