INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering and Technology, Davangere-04
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY MANUAL
Subject code:
Python Programming Laboratory
BCSPLC105A
[As per Choice Based Credit System (CBCS) scheme]
(Effective from the academic year 2024 -2025)
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 1
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
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.
[Link]
Name = input("Enter the name of the student : ")
USN = input("Enter the USN of the student : ")
Marks1 = int(input("Enter marks in Subject 1 : "))
Marks2 = int(input("Enter marks in Subject 2 : "))
Marks3 = int(input("Enter marks in Subject 3 : "))
Total= Marks1+Marks2+Marks3
Percentage=(Marks1+Marks2+Marks3)/3)
print("************Student Details\n************")
print("Name :", Name)
print("USN :", USN)
print("Marks 1 :", Marks1)
print("Marks 2 :", Marks2)
print("Marks 3 :", Marks3)
print("Total :", Total)
print("Percent :", Percentage)
OUTPUT:
Enter the name of the student : SBR
Enter the USN of the student : 4BD24CG100 Enter
marks in Subject 1 : 50
Enter marks in Subject 2 : 68
Enter marks in Subject 3 : 98
Student Details
=========================
Name : SBR
USN : 4BD24CG100
Marks 1 : 50
Marks 2 : 68
Marks 3 : 98
Total : 216
Percent : 72.0
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 2
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
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.
[Link]
from datetime import date
Name = input("Enter the name of the person : ")
DOB = int(input("Enter his year of birth : "))
currentyear = [Link]().year
Age = currentyear - DOB
if (Age > 60):
print(Name, "is a Senior Citizen.")
else:
print(Name,"is not a Senior Citizen.")
OUTPUT:
Enter the name of the person: SBR
Enter the year of birth: 1986
SBR is not a Senior Citizen.
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 3
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
2a. Develop a program to generate Fibonacci sequence of length (N). Read N from
the console
[Link]
n = int(input("Enter the Fibonacci sequence length to be generated : "))
firstnumber = 0
secondnumber = 1
print("The Fibonacci series with", n, "terms is :")
print(firstnumber)
print(secondnumber)
for i in range(2,n):
newnumber= firstnumber + secondnumber
print(newnumber)
firstnumber = secondnumber
secondnumber = newnumber
OUTPUT:
Enter the Fibonacci sequence length to be generated: 5
The Fibonacci series with 5 term is:
0 1 1 2 3
# Recursive Python program to display the Fibonacci sequence
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms= int(input("Enter the Fibonacci sequence length to be generated : "))
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 4
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
b. Write a function to calculate the factorial of a number. Develop a program to compute
the binomial coefficient (Given N and R).
[Link]
def fact(num):
if num == 0:
return 1
else:
return num * fact(num - 1)
n = int(input("Enter the value of N : "))
r = int(input("Enter the value of R (R cannot be negative or greater than N): "))
nCr = fact(n)/(fact(r)*fact(n-r))
print(n,'C',r," = ","%d"%nCr,sep="")
OUTPUT:
Enter the value of N: 5
Enter the value of R (R cannot be negative or greater than N): 2
5 C 2 = 10.0
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 5
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
3. Read N numbers from the console and create a list. Develop a program to print mean,
variance and standard deviation with suitable messages.
[Link]
import math
mylist = [ ]
n = int(input("Enter the number of elements: "))
for i in range(n):
val = int(input("Enter the element : "))
[Link](val)
print('The length of list1 is', len(mylist))
print('List Contents', mylist)
mean = sum(mylist) / n
total = 0
for elem in mylist:
total += (elem - mean) ** 2
variance = total / n
stddev = [Link](variance)
print("Mean =", mean)
print("Variance =", variance)
print("Standard Deviation =", stddev)
OUTPUT:
Enter the number of elements: 3
Enter the element : 10
Enter the element : 20
Enter the element : 30
The length of list1 is 3
List Contents [10, 20, 30]
Mean = 20.0
Variance = 66.66666666666667
Standard Deviation = 8.16496580927726
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 6
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
4. Read a multi-digit number (as chars) from the console. Develop a program to
print the frequency of each digit with a suitable message.
[Link]
n = input("Enter a number : ")
freq = { }
for i in n:
if i in freq:
freq[i] += 1
else:
freq[i] = 1
# printing result
print("Frequency of all characters is :", freq)
OUTPUT:
Enter a number: 1231234124
Frequency of all characters is: {'1': 3, '2': 3, '3': 2, '4': 2}
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 7
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
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]
[Link]
file=open("D://[Link]") # Provide the path of note pad file
text=[Link]( ) # Read the file and store it in text
print(text)
words=[Link]( ) # split the text considering space between words
frequency={ } # Create a dictionary frequency
for word in words:
if word not in frequency: # Code will check whether the word is already
frequency[word]=1 # present in the dictionary if present it will execute else
else: # condition and increment frequency , if not present it will
frequency[word]+=1 # add word to the dictionary
#print(frequency)
most_frequent = dict(sorted([Link](),key=lambda elem: elem[1],reverse=True))
# sort in descending order
#print(most_frequent)
out = dict(list(most_frequent.items())[0: 10]) # select the top 10 most frequently used
words
print("1st 10 Most Frequent words are:"+str(out)) # print the output
Input: [Link]
Once upon a time there lived a poor widow and her son Jack. One day, Jack‟s mother
told him to sell their only cow. Jack went to the market and on the way he met a man
who wanted to buy his cow
Output:
1st 10 Most Frequent words are :{'a': 3, 'to': 3, 'and': 2, 'Jack': 2, 'the': 2, 'Once':
1, 'upon': 1, 'time': 1, 'there': 1, 'lived': 1}
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 8
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
[Link] 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()].
[Link]
f = open("[Link]")
words = []
for line in f:
temp = [Link]()
for i in temp:
[Link](i)
[Link]()
[Link]()
outfile = open("[Link]", "w")
for i in words:
[Link](i)
[Link](" ")
[Link]()
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 9
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
7. Implement a Python program to perform the following operations on an Excel
spreadsheet:
• Reading the first 5 rows of all columns
• Appending a new row / new column
• Delete row/column
• To perform aggregate functions
[Link]
import pandas as pd
# Load the Excel file into a DataFrame
df = pd.read_excel("d:/[Link]")
# 1. Reading the first 5 rows of all columns
print("First 5 rows of all columns:")
print([Link]()) # Shows the first 5 rows
# 2. Appending a new row (example: a row with new values)
# Define the new row to append (keys match existing column names)
new_row = {'Name': 'ABC', 'USN': '4BD21CS83', 'Marks1': 24, 'Marks2': 10,
'Marks3': 30} # Match column names exactly
# Convert the new row to a DataFrame and use [Link] to append it
new_row_df = [Link]([new_row]) # Create a single-row DataFrame
df = [Link]([df, new_row_df], ignore_index=True) # Append the new row
print("\nDataFrame after appending a new row:")
print(df)
# Save the updated DataFrame back to Excel if needed
df.to_excel('D:\\example_updated.xlsx', index=False)
# 3. Appending a new column
# Add a new column with default values or calculated values
df['AverageMarks'] = df[['Marks1', 'Marks2', 'Marks3']].mean(axis=1) # Calculate
row-wise mean
print("\nDataFrame after adding a new column:")
print(df)
# 4. Deleting a row by index (example: delete the row with index 2)
# First, get the 'Name' of the row being deleted
deleted_row = [Link][2] # Access row with index 2
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 10
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
print(f"\nDeleted Row Name: {deleted_row['Name']}") # Replace 'Name' with the actual
column name for names
# Delete the row
df = [Link](index=2)
print("\nDataFrame after deleting a row:")
print(df)
#5. Deleting a column by name (example: delete the 'Marks3' column)
deleted_column = 'Marks3' # Specify the column name to delete
df = [Link](columns=[deleted_column]) # Drop the column
print(f"\nDataFrame after deleting the column '{deleted_column}':")
print(df)
# 6. Perform aggregate functions (e.g., mean, sum)
# Only apply mean to numeric columns
print("\nMean of each numeric column:")
print(df.select_dtypes(include='number').mean())
print("\nSum of each numeric column:")
print(df.select_dtypes(include='number').sum())
# Save the modified DataFrame back to Excel (optional)
df.to_excel('modified_excel_file.xlsx', index=False) # Replace with your desired file
path
OUTPUT:
Input File:'D:\\example_updated.xlsx'
First 5 rows of all columns:
Name USN Marks1 Marks2 Marks3
0 Sreenivasa B R 4BD15CS21 20 30 25
1 Razak 4BD15CS13 10 30 28
2 Vinayak 4BD18CS23 21 12 26
3 Amrutha 4BD16CS32 23 17 27
4 Santhosh 4BD22CS65 26 25 26
DataFrame after appending a new row:
Name USN Marks1 Marks2 Marks3
0 Sreenivasa B R 4BD15CS21 20 30 25
1 Razak 4BD15CS13 10 30 28
2 Vinayak 4BD18CS23 21 12 26
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 11
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
3 Amrutha 4BD16CS32 23 17 27
4 Santhosh 4BD22CS65 26 25 26
5 ABC 4BD21CS83 24 10 30
DataFrame after adding a new column:
Name USN Marks1 Marks2 Marks3 AverageMarks
0 Sreenivasa B R 4BD15CS21 20 30 25 25.000000
1 Razak 4BD15CS13 10 30 28 22.666667
2 Vinayak 4BD18CS23 21 12 26 19.666667
3 Amrutha 4BD16CS32 23 17 27 22.333333
4 Santhosh 4BD22CS65 26 25 26 25.666667
5 ABC 4BD21CS83 24 10 30 21.333333
Deleted Row Name: Vinayak
DataFrame after deleting a row:
Name USN Marks1 Marks2 Marks3 AverageMarks
0 Sreenivasa B R 4BD15CS21 20 30 25 25.000000
1 Razak 4BD15CS13 10 30 28 22.666667
3 Amrutha 4BD16CS32 23 17 27 22.333333
4 Santhosh 4BD22CS65 26 25 26 25.666667
5 ABC 4BD21CS83 24 10 30 21.333333
DataFrame after deleting the column 'Marks3':
Name USN Marks1 Marks2 AverageMarks
0 Sreenivasa B R 4BD15CS21 20 30 25.000000
1 Razak 4BD15CS13 10 30 22.666667
3 Amrutha 4BD16CS32 23 17 22.333333
4 Santhosh 4BD22CS65 26 25 25.666667
5 ABC 4BD21CS83 24 10 21.333333
Mean of each numeric column:
Marks1 20.6
Marks2 22.4
AverageMarks 23.4
dtype: float64
Sum of each numeric column:
Marks1 103.0
Marks2 112.0
AverageMarks 117.0
dtype: float64
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 12
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
8. Write a function named DivExp which takes two parameters a, b returns 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.
[Link]
def DivExp(a,b):
try:
assert a > 0, "a should be greater than 0."
# Raise an exception if b is 0
if b == 0:
raise ZeroDivisionError("Division by zero is not allowed.")
# Perform the division
c = a / b
print("The result of division is:", c)
except Exception as e:
print(e)
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
DivExp(a,b)
Output:
Enter the value of a:15
Enter the value of b:8
The result of division is: 1.875
Enter the value of a:0
Enter the value of b:20
a should be greater than 0
Enter the value of a:25
Enter the value of b:0
Division by zero is not allowed.
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 13
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
9. Define a function that takes TWO objects representing complex numbers and
returns a new complex number with the 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.
[Link]
class Complex:
def __init__(self, real, imag):
"""
Initialize a complex number with a real and imaginary part.
"""
[Link] = real
[Link] = imag
def __add__(self, other):
"""
Add two complex numbers using operator overloading.
"""
return Complex([Link] + [Link], [Link] + [Link])
def __str__(self):
"""
String representation of the complex number in 'a + bi' format.
"""
return f"{[Link]} + {[Link]}i"
def add_complex_numbers(complex_list):
"""
Takes a list of Complex objects and returns their sum.
"""
result = Complex(0, 0)
for complex_number in complex_list:
result += complex_number
return result
# Main Program
N = int(input("Enter the number of complex numbers (N >= 2): "))
if N < 2:
print("N must be at least 2.")
else:
complex_numbers = [ ]
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 14
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
# Read N complex numbers
for i in range(N):
real = float(input(f"Enter the real part of complex number {i + 1}: "))
imag = float(input(f"Enter the imaginary part of complex number {i + 1}: "))
complex_numbers.append(Complex(real, imag))
# Compute the sum
total = add_complex_numbers(complex_numbers)
# Display the result
print("\nThe sum of the complex numbers is:", total)
Output:
Enter the number of complex numbers (N >= 2): 2
Enter the real part of complex number 1: 2
Enter the imaginary part of complex number 1: 3
Enter the real part of complex number 2: 4
Enter the imaginary part of complex number 2: 7
The sum of the complex numbers is: 6.0 + 10.0i
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 15
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
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.]
[Link]
class Student:
def __init__(self, name, usn):
"""
Initializes the student's details: name, USN, marks list, and total.
"""
[Link] = name
[Link] = usn
[Link] = [] # List to store marks of three subjects
[Link] = 0 # Variable to store total marks
def getMarks(self):
"""
Prompts the user to enter marks for 3 subjects and stores them in the marks list.
"""
for i in range(3):
mark = float(input(f"Enter marks for subject {i + 1}: "))
[Link](mark)
def calculateTotal(self):
"""
Calculates total marks and percentage.
"""
[Link] = sum([Link])
[Link] = ([Link] / 300) * 100 # Assuming each subject is out of 100
def display(self):
"""
Displays the student's score card details.
"""
print("\n---------- Score Card ----------")
print(f"Name: {[Link]}")
print(f"USN: {[Link]}")
print(f"Marks in subjects: {[Link]}")
print(f"Total Marks: {[Link]}")
print(f"Percentage: {[Link]:.2f}%")
print("-------------------------------")
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 16
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [24CSPLC15B/24CSPLC25B]
# Main Program
name = input("Enter student's name: ")
usn = input("Enter student's USN: ")
# Create a Student object
student = Student(name, usn)
# Read marks, calculate total and percentage, and display score card
[Link]()
[Link]()
[Link]()
Output:
Enter student's name: John Doe
Enter student's USN: 1BS19CS001
Enter marks for subject 1: 80
Enter marks for subject 2: 90
Enter marks for subject 3: 85
---------- Score Card ----------
Name: John Doe
USN: 1BS19CS001
Marks in subjects: [80.0, 90.0, 85.0]
Total Marks: 255.0
Percentage: 85.00%
-------------------------------
Dr. Sreenivasa B R, Professor, Dept. of CS&D, BIET 17