0% found this document useful (0 votes)
4 views

Python Manual

This document is a lab manual for an Introduction to Python Programming course at a city engineering college, outlining the course objectives, program outcomes, and specific programming exercises for students. It includes a vision and mission statement for the department, program education objectives, and a series of programming tasks designed to enhance students' skills in Python. The exercises cover various topics such as data input/output, mathematical computations, file handling, and object-oriented programming.

Uploaded by

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

Python Manual

This document is a lab manual for an Introduction to Python Programming course at a city engineering college, outlining the course objectives, program outcomes, and specific programming exercises for students. It includes a vision and mission statement for the department, program education objectives, and a series of programming tasks designed to enhance students' skills in Python. The exercises cover various topics such as data input/output, mathematical computations, file handling, and object-oriented programming.

Uploaded by

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

CITY

ENGINEERING COLLEGE
(Doddakallsandra, off. Kanakapura Road, Bangalore – 560061)
NAAC ACCREDITED
Affiliated to Visvesvaraya Technological University, Belagavi
Approved by AICTE, New Delhi

LAB MANUAL

INTRODUCTION TO PYTHON PROGRAMMING


(Subject Code: BPLCK105B/205B)

For

B.E, I/II SEMESTER

NAME:

USN:
SEMESTER & SECTION:

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


ACADEMIC YEAR: 2023-2024
VISION
Making Remarkable Contribution by Disseminating Knowledge on Emerging
Trends in Engineering and Technology through various Programmes, Innovation
and Research so as to Excel in Quality both at National and International level
and to provide Career Guidance & Training for Employment.

MISSION
M1- To encourage Knowledge Acquisition and Foster Innovation & Research.

M2- To Prepare Students for Immediate Employment, leading to Technological


and Socio- economical growth.

M3- To Provide Guidance for a Productive Career under various programmes.


PROGRAM OUTCOMES (PO)
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 andwrite
effective reports and design documentation, make effective presentations, and give andreceive
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.

Program Specific Outcome


Computer Science & Engineering: Graduates are able to Analyze, Design and Construct
Civil Engineering systems with state-of-the art Technologies.
DEPARTMENT VISION AND MISSION

VISION:
To contribute to Global Development by producing Knowledgeable and Quality professionals
who are Innovative and Successful in advanced field of Computer Science & Engineering to
adapt the changing Employment demands and social needs.

MISSION:
M1: To provide Quality Education for students, to build Confidence by developing their
Technical Skills to make them Competitive Computer Science Engineers.
M2: To facilitate Innovation & Research for students and faculty and to provide Internship
opportunities
M3: To Collaborate with educational institutions and industries for Excellence in Teaching
and Research.

PROGRAM EDUCATION OBJECTIVES (PEO):


PEO1: Graduates will have strong foundation in Basic Engineering Sciences that are
required for problem solving to succeed in their profession.
PEO2: Graduates will have scientific and engineering knowledge in cutting edge
technologies so as to design and solve real life problems using the acquired skills and
lifelong learning.
PEO3: Graduates will be professionals with ethics, good communication skills, teamwork
capability, and relate engineering problems with social context.

PROGRAM SPECIFIC OUTCOME (PSO):


Graduates will be Proficient with Analytical and Logical skills and will be able to Design,
Develop, Test and Maintain software and computer systems in phase with the advancing
technology.
Introduction to Python Programming
BPLCK105B/205B
Programming Exercises
1a. 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
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.]
1a)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.

stName = input("Enter the name of the student : ")


stUSN = input("Enter the USN of the student : ")
stMarks1 = int(input("Enter marks in Subject 1 : "))
stMarks2 = int(input("Enter marks in Subject 2 : "))
stMarks3 = int(input("Enter marks in Subject 3 : "))
print("Student Details\n=========================")
print("Name :", stName)
print("USN :", stUSN)
print("Marks 1 :", stMarks1)
print("Marks 2 :", stMarks2)
print("Marks 3 :", stMarks3)
print("Total :", stMarks1+stMarks2+stMarks3)
percent=((stMarks1+stMarks2+stMarks3)/300)*100
print("Percent :",percent)
if percent<35:
print("student",stName , "has failed")
else:
print("Student",stName, "has passed")

print("=========================")

OUTPUT1:
Enter the name of the student : Mark
Enter the USN of the student : 22sas
Enter marks in Subject 1 : 52
Enter marks in Subject 2 : 45
Enter marks in Subject 3 : 78
Student Details
=========================
Name : Mark
USN : 22sas
Marks 1 : 52
Marks 2 : 45
Marks 3 : 78
Total : 175
Percent : 58.333333333333336
Student Mark has passed
=========================
OUTPUT2:
Enter the name of the student : James
Enter the USN of the student : 22SBS
Enter marks in Subject 1 : 25
Enter marks in Subject 2 : 32
Enter marks in Subject 3 : 33
Student Details
=========================
Name : James
USN : 22SBS
Marks 1 : 25
Marks 2 : 32
Marks 3 : 33
Total : 90
Percent : 30.0
student James has failed
=========================
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.

from datetime import date


perName = input("Enter the name of the person : ")
perDOB = int(input("Enter his year of birth : "))
curYear = date.today().year
perAge = curYear - perDOB
if (perAge > 60):
print(perName, "aged", perAge, "years is a Senior Citizen.")
else:
print(perName, "aged", perAge, "years is not a Senior Citizen.")

OUTPUT1:
Enter the name of the person : MARK
Enter his year of birth : 1961
MARK aged 62 years is a Senior Citizen.

OUTPUT2:
Enter the name of the person : SCOTT
Enter his year of birth : 2014
SCOTT aged 9 years is not a Senior Citizen.
2. a. Develop a program to generate Fibonacci sequence of length (N). Read N from the
console.

nterms = int(input("Enter N? "))


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

OUTPUT:
Enter N? 5
Fibonacci sequence:
0
1
1
2
3
2.b. Write a function to calculate factorial of a number. Develop a program to compute
binomial coefficient (Given N and R).

def binomialCoeff(n, k):


if k > n:
return 0
if k == 0 or k == n:
return 1
# Recursive Call
return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k)

n= int(input("Enter a number N: "))


k=int(input("Enter value of K: "))
factorial = 1
if n < 0:
print(" Factorial does not exist for negative numbers")
elif n== 0:
print("The factorial of 0 is 1")
else:
for i in range(1,n + 1):
factorial = factorial*i
print("The factorial of",n,"is",factorial)
print("Value of C(%d,%d) is (%d)" % (n, k, binomialCoeff(n, k)))

OUTPUT:
Enter a number N: 5
Enter value of K: 2
The factorial of 5 is 120
Value of C(5,2) is (10)
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 numpy as np
lst = []
# number of elements as input
n = int(input("Enter number of elements : "))
# iterating till the range
for i in range(0, n):
ele = int(input())
lst.append(ele) # adding the element
print("list elements are",lst)
print("mean is" ,np.average(lst))
print("variance is" ,np.var(lst))
print("standars deviation is",np.std(lst))

OUTPUT:
Enter number of elements : 5
1
2
3
4
5
list elements are [1, 2, 3, 4, 5]
mean is 3.0
variance is 2.0
standars deviation is 1.4142135623730951
4. Read a multi-digit number (as chars) from the console. Develop a program to print the
frequency of each digit with suitable message.

def char_frequency(str1):
dict = {}
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
return dict
str1=input("Enter the multi-digit number: ")
print(char_frequency(str1))

OUTPUT:
Enter the multi-digit number: 55667888
{'5': 2, '6': 2, '7': 1, '8': 3}
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]
text = open("sample.txt", "r")

# Create an empty dictionary


d = dict()

# Loop through each line of the file


for line in text:
# Remove the leading spaces and newline character
line = line.strip()

# Convert the characters in line to


# lowercase to avoid case mismatch
line = line.lower()

# Split the line into words


words = line.split(" ")

# Iterate over each word in line


for word in words:
# Check if the word is already in dictionary
if word in d:
# Increment count of word by 1
d[word] = d[word] + 1
else:
# Add the word to dictionary with count 1
d[word] = 1

# Print the contents of dictionary


for key in list(d.keys()):
print(key, ":", d[key])
OUTPUT:
mango : 3
banana : 3
apple : 3
pear : 2
grapes : 1
strawberry : 2
kiwi : 1
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()].

def sorting(filename):
infile = open(filename)
words = []
for line in infile:
temp = line.split()
for i in temp:
words.append(i)
infile.close()
words.sort()
outfile = open("result.txt", "w")
for i in words:
outfile.writelines(i)
outfile.writelines(" ")
outfile.close()
sorting("sample.txt")
7. Develop a program to backing Up a given Folder (Folder in a current working directory) into
a ZIPFile by using relevant modules and suitable methods.

from zipfile import ZipFile


import os
def get_all_file_paths(directory):
# initializing empty file paths list
file_paths = []

# crawling through directory and subdirectories


for root, directories, files in os.walk(directory):
for filename in files:
# join the two strings in order to form the full filepath.
filepath = os.path.join(root, filename)
file_paths.append(filepath)

# returning all file paths


return file_paths

def main():
# path to folder which needs to be zipped
directory = './python_files'

# calling function to get all file paths in the directory


file_paths = get_all_file_paths(directory)
# printing the list of all files to be zipped
print('Following files will be zipped:')
for file_name in file_paths:
print(file_name)
# writing files to a zipfile
with ZipFile('my_python_files.zip','w') as zip:
# writing each file one by one
for file in file_paths:
zip.write(file)
print('All files zipped successfully!')
if __name__ == "__main__":
main()
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):
try:
c=a/b
print("Quotient:",c)
except ZeroDivisionError:
print("Division by Zero!")
a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
result=(DivExp(a,b))

OUTPUT:
Enter the value of a:5
Enter the value of b:0
Division by Zero!
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:

# Constructor to accept
# real and imaginary part
def __init__(self, tempReal, tempImaginary):
self.real = tempReal;
self.imaginary = tempImaginary;

# Defining addComp() method


# for adding two complex number
def addComp(self, C1, C2):

# creating temporary variable


temp=Complex(0, 0)

# adding real part of complex numbers


temp.real = C1.real + C2.real;

# adding Imaginary part of complex numbers


temp.imaginary = C1.imaginary + C2.imaginary;

# returning the sum


return temp;

# Driver code
if __name__=='__main__':

# First Complex number


C1 = Complex(3, 2);

# printing first complex number


print("Complex number 1 :", C1.real, "+ i" + str(C1.imaginary))
# Second Complex number
C2 = Complex(9, 5);

# printing second complex number


print("Complex number 2 :", C2.real, "+ i" + str(C2.imaginary))

# for Storing the sum


C3 = Complex(0, 0)

# calling addComp() method


C3 = C3.addComp(C1, C2);

# printing the sum


print("Sum of complex number :", C3.real, "+ i"+ str(C3.imaginary))

OUTPUT:
Complex number 1 : 3 + i2
Complex number 2 : 9 + i5
Sum of complex number : 12 + i7
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 = ""):
self.name = name
self.usn = usn
def getStudentDetails(self):
self.usn=input("Enter USN : ")
self.name = input("Enter Name : ")
self.subject1 =int(input("Enter subject1 marks : "))
self.subject2 = int(input("Enter subject2 Marks : "))
self.subject3 = int(input("Enter subject3 Marks : "))
def printResult(self):
self.total=(int)(self.subject1 + self.subject2 + self.subject3)
self.percentage = (int)( (self.subject1 + self.subject2 + self.subject3) / 300 * 100 );
print("USN Name total percentage")
print(self.usn,self.name,self.total,self.percentage)
if self.percentage<35:
print("student",self.name , "has failed")
else:
print("Student",self.name, "has passed")
S1=Student()
S1.getStudentDetails()
print("Result : ")
S1.printResult()

OUTPUT1:
Enter USN : 12
Enter Name : Mark
Enter subject1 marks : 87
Enter subject2 Marks : 66
Enter subject3 Marks : 55
Result :
USN Name total percentage
12 Mark 208 69
Student Mark has passed

OUTPUT2:
Enter USN : 11
Enter Name : James
Enter subject1 marks : 23
Enter subject2 Marks : 11
Enter subject3 Marks : 15
Result :
USN Name total percentage
11 James 49 16
student James has failed

You might also like