Python 2nd Sem LAB MANUAL 2023-24
Python 2nd Sem LAB MANUAL 2023-24
Student Name:
USN:
Section: Batch:
PREFACE
Python has gained immense popularity in recent years due to its simplicity, readability, and
versatility. It is widely used in various domains such as web development, data science, artificial
intelligence, automation, and more. Learning Python will not only equip you with a valuable skill
set but also open up a plethora of opportunities in the rapidly evolving tech industry.
This laboratory is structured to be interactive and hands-on. You will have the opportunity
to write code, experiment with different concepts, and solve programming challenges. Each
exercise is carefully crafted to reinforce key concepts and build upon your understanding
progressively.
Each topic will be accompanied by examples, exercises, and practical projects to reinforce
your learning. Additionally, you will have access to resources such as documentation, tutorials,
and online forums to support your learning journey outside of the laboratory.
By the end of this laboratory, you will have a solid understanding of Python programming
concepts and the confidence to tackle more advanced topics. Remember, programming is a skill
that improves with practice, so make sure to spend time coding outside of the laboratory
assignments to reinforce what you've learned.
Institute Vision
Institute Mission
Department Vision
To become a Center of Excellence in the computer science and information technology discipline
with a strong research and teaching environment that produces highly qualified and motivated
graduates.
Department Mission
PO2 Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences
PO3 Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations
PO4 Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
PO6 The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice
PO7 Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development
PO8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice
PO9 Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO10 Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
PO11 Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
PEO (Program Educational Objectives)
• Understand, analyse and realise the concepts in the field of analog and digital signal
processing, communication, networking and semiconductor technology by applying
modern design tools.
• Ability to enrich the design in electronics through optimization, better efficiency and
innovative ideas
• Enabling the graduates with excellent technical and soft skills, lifelong learning, leadership
qualities, ethics and societal responsibilities.
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY
Course Code: BPLCK205B
Programming Experiments
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.
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.
2. a. Develop a program to generate Fibonacci sequence of length (N). Read N from the
console.
b. Write a function to calculate factorial of a number. Develop a program to compute
binomial coefficient (Given N and R).
3. Read N numbers from the console and create a list. Develop a program to print mean,
variance and standard deviation with suitable messages.
4. Read a multi-digit number (as chars) from the console. Develop a program to print the
frequency of each digit with suitable message.
5. Develop a program to print 10 most frequently appearing words in a text file. [Hint: Use
dictionary 16-2-2023 3 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]
6. Develop a program to sort the contents of a text file and write the sorted contents into a
separate text file. [Hint: Use string methods strip(), len(), list methods sort(), append(), and
file methods open(), readlines(), and write()].
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.
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.
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.
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.]
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
Source code
class Student:
def __init__(self, name, usn, marks):
self.name = name
self.usn = usn
self.marks = marks
def display_details(self):
total_marks = sum(self.marks)
percentage = (total_marks / (len(self.marks) * 100)) * 100
print("Student Details:")
print("Name:", self.name)
print("USN:", self.usn)
print("Marks:", self.marks)
print("Total Marks:", total_marks)
print("Percentage:", percentage, "%")
def main():
name = input("Enter student's name: ")
usn = input("Enter student's USN: ")
marks = [int(input("Enter marks for subject {} (out of 100): ".format(i+1))) for i in range(3)]
student = Student(name, usn, marks)
student.display_details()
if __name__ == "__main__":
main()
OUTPUT
1b. Develop a program to read the name and year of birth of a person. Display whether the
person is a senior citizen or not.
Source code
class Person:
def __init__(self, name, year_of_birth):
self.name = name
self.year_of_birth = year_of_birth
def is_senior_citizen(self):
return datetime.now().year - self.year_of_birth >= 60
OUTPUT
2.a. Develop a program to generate Fibonacci sequence of length (N). Read N from the
console.
Source code
def generate_fibonacci_sequence(length):
sequence = [0, 1]
for _ in range(2, length):
sequence.append(sequence[-1] + sequence[-2])
return sequence[:length]
def main():
try:
N = int(input("Enter the length of Fibonacci sequence: "))
if N <= 0:
print("Length should be a positive integer.")
else:
print("Fibonacci sequence of length", N, ":", generate_fibonacci_sequence(N))
except ValueError:
print("Invalid input! Please enter a valid integer.")
if __name__ == "__main__":
main()
OUTPUT
2b. Write a function to calculate factorial of a number. Develop a program to compute
binomial coefficient (Given N and R).
Source code
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
def main():
try:
N = int(input("Enter the value of N: "))
R = int(input("Enter the value of R: "))
if N < 0 or R < 0:
print("N and R should be non-negative integers.")
else:
coefficient = binomial_coefficient(N, R)
print("Binomial coefficient of (", N, ",", R, "):", coefficient)
except ValueError:
print("Invalid input! Please enter valid integers for N and R.")
if __name__ == "__main__":
main()
OUTPUT
3. Read N numbers from the console and create a list. Develop a program to print mean,
variance and standard deviation with suitable messages.
Source code:
import math
def main():
try:
N = int(input("Enter the number of elements: "))
numbers = [float(input("Enter number {}: ".format(i+1))) for i in range(N)]
mean = sum(numbers) / N
variance = sum((x - mean) ** 2 for x in numbers) / N
std_deviation = math.sqrt(variance)
print("Mean:", mean)
print("Variance:", variance)
print("Standard Deviation:", std_deviation)
except ValueError:
print("Invalid input! Please enter valid numbers.")
if __name__ == "__main__":
main()
OUTPUT:
4.Read a multi-digit number (as chars) from the console. Develop a program to print the
frequency of each digit with suitable message.
Source code:
def main():
try:
num_str = input("Enter a multi-digit number: ")
digit_freq = {str(i): 0 for i in range(10)}
for digit in num_str:
if digit.isdigit():
digit_freq[digit] += 1
print("Frequency of each digit:")
for digit, freq in digit_freq.items():
print("Digit:", digit, "- Frequency:", freq)
except ValueError:
print("Invalid input! Please enter a valid multi-digit number.")
if __name__ == "__main__":
main()
OUTPUT:
5.Develop a program to print 10 most frequently appearing words in a text file. [Hint: Use
dictionary 16-2-2023 3 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]
Source code:
def main():
try:
file_name = input("Enter the name of the text file: ")
with open(file_name, 'r') as file:
words = file.read().split()
word_freq = Counter(words)
sorted_word_freq = dict(sorted(word_freq.items(), key=lambda item: item[1], reverse=True))
except FileNotFoundError:
print(f"The file '{file_name}' was not found.")
except Exception as e:
print("An error occurred:", str(e))
if __name__ == "__main__":
main()
6.Develop a program to sort the contents of a text file and write the sorted contents into a
separate text file. [Hint: Use string methods strip(), len(), list methods sort(), append(), and
file methods open(), readlines(), and write()].
Source code:
def main():
try:
input_file_name = input("Enter the name of the input text file: ")
with open(input_file_name, 'r') as input_file:
lines = input_file.readlines()
lines.sort()
output_file_name = input_file_name.split('.')[0] + "_sorted.txt"
with open(output_file_name, 'w') as output_file:
for line in lines:
output_file.write(line)
print(f"The sorted contents have been written to '{output_file_name}'.")
except FileNotFoundError:
print(f"The file '{input_file_name}' was not found.")
except Exception as e:
print("An error occurred:", str(e))
if __name__ == "__main__":
main()
OUTPUT:
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.
Source code
import os
import zipfile
def backup_folder_to_zip(folder_path):
if not os.path.exists(folder_path):
print(f"The folder '{folder_path}' does not exist.")
return
folder_name = os.path.basename(folder_path)
zip_file_name = f"{folder_name}_backup.zip"
if __name__ == "__main__":
folder_to_backup = input("Enter the folder path to backup: ").strip()
backup_folder_to_zip(folder_to_backup)
OUTPUT:
Source code:
if __name__ == "__main__":
try:
a = float(input("Enter the value of 'a': "))
b = float(input("Enter the value of 'b': "))
result = DivExp(a, b)
print(f"Result of division: {result}")
except ValueError as ve:
print(f"Error: {ve}")
except AssertionError as ae:
print(f"Assertion Error: {ae}")
OUTPUT:
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.
SOURCE CODE:
class Complex:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def add_complex_numbers(complex_numbers):
result = Complex(0, 0)
for num in complex_numbers:
result.real += num.real
result.imaginary += num.imaginary
return result
if __name__ == "__main__":
N = int(input("Enter the number of complex numbers to add (N >= 2): "))
complex_numbers = [Complex(*map(float, input(f"Enter the real and imaginary parts of
complex number {i+1}: ").split())) for i in range(N)]
result = add_complex_numbers(complex_numbers)
print("The sum of the complex numbers is:", result.real, "+", result.imaginary, "i")
OUTPUT:
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.]
SOURCE CODE:
class Student:
def __init__(self, name, usn):
self.name = name
self.usn = usn
self.marks = []
self.total_marks = 0
def get_marks(self):
for i in range(3):
mark = float(input(f"Enter marks for subject {i+1}: "))
self.marks.append(mark)
self.total_marks += mark
def display(self):
print("Score Card Details:")
print("Name:", self.name)
print("USN:", self.usn)
print("Marks obtained in each subject:", self.marks)
print("Total marks:", self.total_marks)
print("Percentage:", (self.total_marks / 300) * 100)
if __name__ == "__main__":
name = input("Enter student name: ")
usn = input("Enter student USN: ")
OUTPUT: