0% found this document useful (0 votes)
107 views18 pages

Python 2nd Sem LAB MANUAL 2023-24

Uploaded by

farhahumera4
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)
107 views18 pages

Python 2nd Sem LAB MANUAL 2023-24

Uploaded by

farhahumera4
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
You are on page 1/ 18

GOVERNMENT OF KARNATAKA

DEPARTMENT OF COLLEGIATE AND TECHNICAL EDUCATION

GOVERNMENT ENGINEERING COLLEGE


(Affiliated to Visvesvaraya Technological University, Belagavi & Approved by AICTE, New Delhi)
Hyderabad Road, Yaramarus Camp,
RAICHUR – 584135
Ph. No:08532-200624,Fax:08532-251151,E-mail:[email protected]

Department of Computer Science and Engineering


INTRODUCTION TO PYTHON PROGRAMMING LABORATORY
Laboratory Manual
[BPLCK205B]
II SEMESTER – B. E
Academic Year – 2023-2024

Student Name:

USN:

Section: Batch:
PREFACE

Welcome to the Python Programming Laboratory! This laboratory is designed to introduce


you to the fundamentals of programming using the Python programming language. Whether you're
a complete beginner or have some prior experience in programming, this laboratory will provide
you with a solid foundation to start your journey into the world of Python programming.

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.

Throughout this laboratory, you will explore topics such as:

1. Basic Syntax: Understand the syntax and structure of Python code.


2. Variables and Data Types: Learn about different data types in Python and how to work
with them.
3. Control Structures: Explore conditional statements and loops to control the flow of your
programs.
4. Functions: Define and use functions to organize your code and make it reusable.
5. Data Structures: Manipulate lists, tuples, dictionaries, and sets to store and manage data
efficiently.
6. File Handling: Read from and write to files using Python.
7. Error Handling: Learn techniques to handle errors and exceptions in your programs.
8. Object-Oriented Programming (OOP): Introduction to OOP principles such as classes,
objects, inheritance, and polymorphism.

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

To be center of Excellence of Higher Learning and Research in Engineering Imparting Ethical,


Environmental and Economic aspects of the Society.

Institute Mission

Commitment in preparing Globally competent Engineers in response to Rapid Technological


growth through dynamic process of Teaching-Learning, Research and Professional Experiences
for the Betterment of the Community.

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

➢ To provide quality education to meet the needs of profession and society.


➢ Provide a learning ambience to enhance innovations, problem solving skills, leadership
qualities, team-spirit and ethical responsibilities.
➢ To develop human potential to its fullest extent so that intellectually capable and
optimistic leaders can emerge in a range of professions.
Program Outcomes (As Specified by NBA)
PO1 Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering problems.

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)

• PEO1: Proficiency to work in multidisciplinary domains, technological advancements


through continuous learning process.

• PEO2: Graduate with moral and ethical values

• PEO3: Explore the research possibilities, innovative practices and entrepreneurship.

PSO (Program Specific Outcomes)

• 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

from datetime import datetime

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

name = input("Enter person's name: ")


year_of_birth = int(input("Enter person's year of birth: "))

person = Person(name, year_of_birth)

print(person.name, "is a senior citizen." if person.is_senior_citizen() else "is not a senior


citizen.")

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 binomial_coefficient(N, R):


if R > N:
return 0
else:
return factorial(N) // (factorial(R) * factorial(N - R))

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:

from collections import Counter

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

print("Top 10 most frequently appearing words:")


for i, (word, freq) in enumerate(sorted_word_freq.items()):
print(f"{i+1}. Word: {word}, Frequency: {freq}")
if i == 4:
break

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

FILE NAME: text.txt

This is a sample text file for testing purposes.


It contains some random words and sentences.
This text file will be used by the program to find the most frequently appearing words.
for
for file
OUTPUT:

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"

with zipfile.ZipFile(zip_file_name, 'w') as backup_zip:


for foldername, subfolders, filenames in os.walk(folder_path):
backup_zip.write(foldername)
for filename in filenames:
file_path = os.path.join(foldername, filename)
backup_zip.write(file_path, os.path.relpath(file_path, folder_path))

print(f"Backup of '{folder_path}' completed successfully. Created '{zip_file_name}'.")

if __name__ == "__main__":
folder_to_backup = input("Enter the folder path to backup: ").strip()
backup_folder_to_zip(folder_to_backup)

OUTPUT:

Enter the folder path to backup: /path/to/your/folder


Backup of '/path/to/your/folder' completed successfully. Created 'folder_backup.zip'.
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.

Source code:

def DivExp(a, b):


assert a > 0, "Value of 'a' must be greater than 0."
if b == 0:
raise ValueError("Division by zero is not allowed.")
return a / b

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

student = Student(name, usn)


student.get_marks()
student.display()

OUTPUT:

You might also like