JSPM University, Pune
School of Computational Sciences
Faculty of Science and Technology
Lab Manual
“Fundamentals of Python Programming”
[Link]. First Year
Course Code: 240GCSB62_01
Academic Year: 2025-26
Created By: Mr. Nilesh Bangar
Experiment 1 a: Display your name, count length of it and display what
will be your age in year.
Aim:
Display your name, count length of it and display what will be your age in year.
Learning Objectives:
• Understand concepts and implementation demonstrated in this experiment.
• Practice Python programming constructs relevant to the task.
Learning Outcomes:
• Able to implement the given program in Python and understand its working.
• Able to analyze input/output and adapt the code for similar tasks.
Theory:
1. Explain how input() and print() work in Python. How does data from input() get
represented by default?
2. How does the len() function determine the length of a string? Give an example with
whitespace and special characters.
3. What error will occur if you try to add 1 to a variable returned directly from input()
without conversion? Why?
Algorithm:
1. Start
2. Input name
3. Compute length using len()
4. Input age
5. Compute age+1
6. Display results
7. End
Flowchart:
Figure 1a: Flowchart for Experiment 1
Code:
# Experiment 1(a)
name = input("Enter your name: ")
print("Your name is:", name)
print("Length of your name:", len(name))
age = int(input("Enter your current age in years: "))
print("Your age after 1 year will be:", age + 1)
Sample Input and Output:
Input:
Enter your name: Alex
Enter your current age in years: 21
Output:
Your name is: Alex
Length of your name: 4
Your age after 1 year will be: 22
Conclusion:
The program implements the stated aim and demonstrates the described concepts. Modify input
values to test other cases.
Experiment 1 b: Arithmetic operations using type conversion.
Aim:
Arithmetic operations using type conversion.
Learning Objectives:
• Understand concepts and implementation demonstrated in this experiment.
• Practice Python programming constructs relevant to the task.
Learning Outcomes:
• Able to implement the given program in Python and understand its working.
• Able to analyze input/output and adapt the code for similar tasks.
Theory:
1. Explain implicit vs explicit type conversion in Python with examples.
2. Why is it safer to convert numeric inputs to float rather than int before performing
arithmetic? Give a use-case.
3. What is the difference in behaviour between / and // operators? Provide sample results.
Algorithm:
1. Start
2. Input a, b (strings)
3. Convert to float
4. Perform + - * /
5. Display results
6. End
Flowchart:
Figure 1.b: Flowchart for Experiment 1
Code:
# Experiment 1(b)
a = input("Enter first number: ")
b = input("Enter second number: ")
# convert to float for arithmetic
a_num = float(a)
b_num = float(b)
print("Addition:", a_num + b_num)
print("Subtraction:", a_num - b_num)
print("Multiplication:", a_num * b_num)
if b_num != 0:
print("Division:", a_num / b_num)
else:
print("Division: Cannot divide by zero")
Sample Input and Output:
Input:
Enter first number: 10
Enter second number: 3
Output:
Addition: 13.0
Subtraction: 7.0
Multiplication: 30.0
Division: 3.3333333333333335
Conclusion:
The program implements the stated aim and demonstrates the described concepts. Modify input
values to test other cases.
Experiment 2: Demonstrate Lists, Tuples, and Dictionaries.
Aim:
Demonstrate Lists, Tuples, and Dictionaries.
Learning Objectives:
• Understand concepts and implementation demonstrated in this experiment.
• Practice Python programming constructs relevant to the task.
Learning Outcomes:
• Able to implement the given program in Python and understand its working.
• Able to analyze input/output and adapt the code for similar tasks.
Theory:
1. Compare and contrast lists and tuples in Python. When would using a tuple be
preferable?
2. Explain how dictionaries store data. How do you access, add, update, and remove items?
3. Describe list comprehension and write a comprehension that produces squares of even
numbers from 1–10.
Algorithm:
1. Start
2. Create list (mutable)
3. Create tuple (immutable)
4. Create dict (key-value)
5. Perform operations
6. Display
7. End
Flowchart:
Figure 3: Flowchart for Experiment 2
Code:
# Experiment 2
# List example
fruits = ["apple", "banana", "cherry"]
[Link]("date")
print("List:", fruits)
# Tuple example
coords = (10, 20)
print("Tuple:", coords)
# Dictionary example
student = {"name": "Alice", "usn": "1AB12CS001", "marks": [78, 85, 92]}
print("Dictionary:", student)
Sample Input and Output:
Output:
List: ['apple', 'banana', 'cherry', 'date']
Tuple: (10, 20)
Dictionary: {'name': 'Alice', 'usn': '1AB12CS001', 'marks': [78, 85, 92]}
Conclusion:
The program implements the stated aim and demonstrates the described concepts. Modify input
values to test other cases.
Experiment 3: Factorial function and Binomial Coefficient (nCr).
Aim:
Factorial function and Binomial Coefficient (nCr).
Learning Objectives:
• Understand concepts and implementation demonstrated in this experiment.
• Practice Python programming constructs relevant to the task.
Learning Outcomes:
• Able to implement the given program in Python and understand its working.
• Able to analyze input/output and adapt the code for similar tasks.
Theory:
1. Write the mathematical definition of factorial and explain how a loop-based and a
recursive implementation differ in Python.
2. What is the time complexity of a factorial function implemented with a simple loop?
3. Explain the formula for binomial coefficient nCr and how factorials are used to compute
it.
Algorithm:
1. Start
2. Input N,R
3. Compute factorials
4. Apply nCr formula
5. Display result
6. End
Flowchart:
Figure 4: Flowchart for Experiment 3
Code:
# Experiment 3
def factorial(n):
if n == 0 or n == 1:
return 1
result = 1
for i in range(2, n+1):
result *= i
return result
def nCr(n, r):
if r > n:
return 0
return factorial(n)//(factorial(r)*factorial(n-r))
n = int(input("Enter N: "))
r = int(input("Enter R: "))
print(f"{n}C{r} =", nCr(n, r))
Sample Input and Output:
Input:
Enter N: 5
Enter R: 2
Output:
5C2 = 10
Conclusion:
The program implements the stated aim and demonstrates the described concepts. Modify input
values to test other cases.
Experiment 4: Check palindrome and count digit occurrences.
Aim:
Check palindrome and count digit occurrences.
Learning Objectives:
• Understand concepts and implementation demonstrated in this experiment.
• Practice Python programming constructs relevant to the task.
Learning Outcomes:
• Able to implement the given program in Python and understand its working.
• Able to analyze input/output and adapt the code for similar tasks.
Theory:
1. Define a palindrome in the context of strings and numbers. How does string reversal
make checking a palindrome simple in Python?
2. Provide two different Python approaches to check if an integer is a palindrome (one using
strings, one using numeric operations).
3. Explain a method to count occurrences of each digit in a number using a dictionary. Why
is [Link](key, 0) useful here?
Algorithm:
1. Start
2. Input number
3. Reverse string
4. Compare
5. Count digits in dict
6. Display
7. End
Flowchart:
Figure 5: Flowchart for Experiment 4
Code:
# Experiment 4
num = input("Enter a number: ")
rev = num[::-1]
if num == rev:
print("The number is a palindrome")
else:
print("The number is not a palindrome")
# Count digits
counts = {}
for ch in num:
counts[ch] = [Link](ch, 0) + 1
print("Digit occurrences:")
for d, c in sorted([Link]()):
print(d, ":", c)
Sample Input and Output:
Input:
Enter a number: 1221
Output:
The number is a palindrome
Digit occurrences:
1:2
2:2
Conclusion:
The program implements the stated aim and demonstrates the described concepts. Modify input
values to test other cases.
Experiment 5: Student details, total marks and percentage.
Aim:
Student details, total marks and percentage.
Learning Objectives:
• Understand concepts and implementation demonstrated in this experiment.
• Practice Python programming constructs relevant to the task.
Learning Outcomes:
• Able to implement the given program in Python and understand its working.
• Able to analyze input/output and adapt the code for similar tasks.
Theory:
1. Explain how lists and loops are used to collect and store multiple related inputs (e.g.,
marks for subjects).
2. How would you validate marks to ensure they are within a valid range (0–100)? Provide
a code sketch.
3. Describe how to format the percentage value to two decimal places in the final output.
Algorithm:
1. Start
2. Input name, USN
3. Input 3 marks
4. Compute total & percentage
5. Display report
6. End
Flowchart:
Figure 6: Flowchart for Experiment 5
Code:
# Experiment 5
name = input("Enter student name: ")
usn = input("Enter USN: ")
marks = []
for i in range(1,4):
m = float(input(f"Enter marks for subject {i}: "))
[Link](m)
total = sum(marks)
percentage = (total/300)*100
print("\nStudent Details:")
print("Name:", name)
print("USN:", usn)
print("Marks:", marks)
print("Total:", total)
print("Percentage:", percentage, "%")
Sample Input and Output:
Input:
Enter student name: John
Enter USN: 1AB12CS002
Enter marks for subject 1: 80
Enter marks for subject 2: 75
Enter marks for subject 3: 85
Output:
Student Details:
Name: John
USN: 1AB12CS002
Marks: [80.0, 75.0, 85.0]
Total: 240.0
Percentage: 80.0 %
Conclusion:
The program implements the stated aim and demonstrates the described concepts. Modify input
values to test other cases.
Experiment 6: Recursive, nested, map/filter/lambda: sum of squares of
even numbers.
Aim:
Recursive, nested, map/filter/lambda: sum of squares of even numbers.
Learning Objectives:
• Understand concepts and implementation demonstrated in this experiment.
• Practice Python programming constructs relevant to the task.
Learning Outcomes:
• Able to implement the given program in Python and understand its working.
• Able to analyze input/output and adapt the code for similar tasks.
Theory:
1. Explain the difference between recursion and iteration. When might recursion be less
suitable?
2. Describe how map, filter, and lambda work. Provide a one-line expression that returns
squares of even numbers from a list.
3. What is a nested function? Give an example where a nested function is useful.
Algorithm:
1. Start
2. Input list
3. Filter even (filter+lambda)
4. Square (map or inner)
5. Sum squares
6. Display
7. End
Flowchart:
Figure 7: Flowchart for Experiment 6
Code:
# Experiment 6
def recursive_sum_squares(nums):
if not nums:
return 0
head, *tail = nums
add = head*head if head%2==0 else 0
return add + recursive_sum_squares(tail)
# nested function example
def outer(nums):
def inner(x):
return x*x
evens = list(filter(lambda x: x%2==0, nums))
squares = list(map(inner, evens))
return sum(squares)
nums = list(map(int, input("Enter numbers separated by space:
").split()))
print("Recursive result:", recursive_sum_squares(nums))
print("Nested/map/filter result:", outer(nums))
Sample Input and Output:
Input:
Enter numbers separated by space: 1 2 3 4 5
Output:
Recursive result: 20
Nested/map/filter result: 20
Conclusion:
The program implements the stated aim and demonstrates the described concepts. Modify input
values to test other cases.
Experiment 7: Employee class and update salary by department.
Aim:
Employee class and update salary by department.
Learning Objectives:
• Understand concepts and implementation demonstrated in this experiment.
• Practice Python programming constructs relevant to the task.
Learning Outcomes:
• Able to implement the given program in Python and understand its working.
• Able to analyze input/output and adapt the code for similar tasks.
Theory:
1. Define the principles of Object-Oriented Programming (OOP) used in this experiment
(encapsulation, attributes, methods).
2. Explain how __init__ works in a Python class and what happens when you create
multiple instances.
3. How would you implement a class method or static method if you wanted to apply a
salary policy across all employees? Give a short code sketch.
Algorithm:
1. Start
2. Create Employee objects
3. Input department & percent
4. Update salary for matching dept
5. Display updated details
6. End
Flowchart:
Figure 8: Flowchart for Experiment 7
Code:
# Experiment 7
class Employee:
def __init__(self, name, emp_id, dept, salary):
[Link] = name
self.emp_id = emp_id
[Link] = dept
[Link] = salary
def update_salary(self, percent):
[Link] = [Link] * (1 + percent/100)
# sample usage
employees = [
Employee("Alice", "E001", "HR", 50000),
Employee("Bob", "E002", "IT", 60000),
Employee("Charlie", "E003", "IT", 55000)
]
dept = input("Enter department to update salary for: ")
percent = float(input("Enter percent increase: "))
for emp in employees:
if [Link]() == [Link]():
emp.update_salary(percent)
print("\nUpdated Employee Details:")
for emp in employees:
print([Link], emp.emp_id, [Link], [Link])
Sample Input and Output:
Input:
Enter department to update salary for: IT
Enter percent increase: 10
Output:
Updated Employee Details:
Alice E001 HR 50000
Bob E002 IT 66000.0
Charlie E003 IT 60500.0
Conclusion:
The program implements the stated aim and demonstrates the described concepts. Modify input
values to test other cases.
Experiment 8: File operations: display first N lines and word frequency.
Aim:
File operations: display first N lines and word frequency.
Learning Objectives:
• Understand concepts and implementation demonstrated in this experiment.
• Practice Python programming constructs relevant to the task.
Learning Outcomes:
• Able to implement the given program in Python and understand its working.
• Able to analyze input/output and adapt the code for similar tasks.
Theory:
1. Describe the modes of open() (e.g., 'r', 'w', 'a', 'rb') and when to use each.
2. Explain how readlines() differs from iterating directly over the file object. Which is more
memory-efficient for large files?
3. Show how to count the frequency of a word in a file in a case-insensitive manner. What
pitfalls must you consider (punctuation, word boundaries)?
Algorithm:
1. Start
2. Input filename & N
3. Read file lines
4. Display first N lines
5. Input word
6. Count occurrences
7. Display count
8. End
Flowchart:
Figure 9: Flowchart for Experiment 8
Code:
# Experiment 8
filename = input("Enter filename: ")
n = int(input("Enter N (number of lines to display): "))
with open(filename, 'r') as f:
lines = [Link]()
print("\nFirst", n, "lines:")
for line in lines[:n]:
print([Link]())
word = input("\nEnter word to count frequency: ")
content = "".join(lines)
count = [Link]().split().count([Link]())
print(f"Occurrences of '{word}':", count)
Sample Input and Output:
Sample Output (assuming file exists):
First 3 lines:
Line1
Line2
Line3
Occurrences of 'the': 5
Conclusion:
The program implements the stated aim and demonstrates the described concepts. Modify input
values to test other cases.
Experiment 9: Math module basic functionalities.
Aim:
Math module basic functionalities.
Learning Objectives:
• Understand concepts and implementation demonstrated in this experiment.
• Practice Python programming constructs relevant to the task.
Learning Outcomes:
• Able to implement the given program in Python and understand its working.
• Able to analyze input/output and adapt the code for similar tasks.
Theory:
1. List at least five useful functions/constants available in the math module and briefly
describe each.
2. What is the difference between [Link](x, y) and the ** operator? Are there cases
where one is preferred?
3. Explain domain errors for functions like [Link]() and [Link]() and how you
would guard against them.
Algorithm:
1. Start
2. Import math
3. Input x
4. Compute sqrt, pow, sin, log
5. Display
6. End
Flowchart:
Figure 10: Flowchart for Experiment 9
Code:
# Experiment 9
import math
x = float(input("Enter a number: "))
print("Square root:", [Link](x))
print("Power (x^3):", [Link](x,3))
print("Sine:", [Link](x))
print("Log (natural):", [Link](x))
Sample Input and Output:
Input:
Enter a number: 4
Output:
Square root: 2.0
Power (x^3): 64.0
Sine: -0.7568024953079282
Log (natural): 1.3862943611198906
Conclusion:
The program implements the stated aim and demonstrates the described concepts. Modify input
values to test other cases.
Experiment 10: Email validation using regex.
Aim:
Email validation using regex.
Learning Objectives:
• Understand concepts and implementation demonstrated in this experiment.
• Practice Python programming constructs relevant to the task.
Learning Outcomes:
• Able to implement the given program in Python and understand its working.
• Able to analyze input/output and adapt the code for similar tasks.
Theory:
1. Explain how regular expressions (regex) are used to validate patterns such as email
addresses. What are the limitations of regex for full email validation?
2. Break down the regex pattern ^[\w\.-]+@[\w\.-]+\.\w+$ and explain each component.
3. Provide an example of a valid email that would fail this simple pattern and explain why it
fails.
Algorithm:
1. Start
2. Input email
3. Match regex pattern
4. Display valid/invalid
5. End
Flowchart:
Figure 11: Flowchart for Experiment 10
Code:
# Experiment 10
import re
email = input("Enter email: ")
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
if [Link](pattern, email):
print("Valid email")
else:
print("Invalid email")
Sample Input and Output:
Input:
Enter email: user@[Link]
Output:
Valid email
Conclusion:
The program implements the stated aim and demonstrates the described concepts. Modify input
values to test other cases.
Experiment 11: Backup a folder into a ZIP file.
Aim:
Backup a folder into a ZIP file.
Learning Objectives:
• Understand concepts and implementation demonstrated in this experiment.
• Practice Python programming constructs relevant to the task.
Learning Outcomes:
• Able to implement the given program in Python and understand its working.
• Able to analyze input/output and adapt the code for similar tasks.
Theory:
1. Explain how the zipfile module is used to create and write ZIP archives. What is the
purpose of ZipFile(..., 'w')?
2. Describe how [Link]() works and why it is suitable for traversing directories to be
backed up.
3. What are potential problems when zipping files that are currently open or in use by other
processes? How might you handle them?
Algorithm:
1. Start
2. Input folder name
3. Traverse folder files
4. Add files to zip
5. Close zip
6. Display zip name
7. End
Flowchart:
Figure 12: Flowchart for Experiment 11
Code:
# Experiment 11
import os, zipfile
folder = input("Enter folder name to backup (in current dir): ")
zip_name = folder + ".zip"
with [Link](zip_name, 'w') as zf:
for root, dirs, files in [Link](folder):
for file in files:
[Link]([Link](root, file))
print("Backup created:", zip_name)
Sample Input and Output:
Input:
Enter folder name to backup (in current dir): mydata
Output:
Backup created: [Link]
Conclusion:
The program implements the stated aim and demonstrates the described concepts. Modify input
values to test other cases.
Experiment 12: Simple GUI application using tkinter.
Aim:
Simple GUI application using tkinter.
Learning Objectives:
• Understand concepts and implementation demonstrated in this experiment.
• Practice Python programming constructs relevant to the task.
Learning Outcomes:
• Able to implement the given program in Python and understand its working.
• Able to analyze input/output and adapt the code for similar tasks.
Theory:
1. Describe the basic architecture of a tkinter application (main window, event loop,
widgets, callbacks).
2. What is [Link]() and what happens if you omit it?
3. Explain how widget geometry managers (e.g., pack, grid, place) differ and when to use
each.
Algorithm:
1. Start
2. Create window & widgets
3. Enter name & click button
4. On click call greet()
5. Display greeting
6. End
Flowchart:
Figure 13: Flowchart for Experiment 12
Code:
# Experiment 12
import tkinter as tk
def greet():
name = [Link]()
label_result.config(text=f"Hello, {name}!")
root = [Link]()
[Link]("Simple Greeting App")
[Link](root, text="Enter your name:").pack()
entry = [Link](root)
[Link]()
[Link](root, text="Greet", command=greet).pack()
label_result = [Link](root, text="")
label_result.pack()
[Link]()
Sample Input and Output:
Run the GUI. Enter a name and click 'Greet' to see the personalized message.
Conclusion:
The program implements the stated aim and demonstrates the described concepts. Modify input
values to test other cases.
Experiment 13: Basic CGI script to accept name and grade and display
message.
Aim:
Basic CGI script to accept name and grade and display message.
Learning Objectives:
• Understand concepts and implementation demonstrated in this experiment.
• Practice Python programming constructs relevant to the task.
Learning Outcomes:
• Able to implement the given program in Python and understand its working.
• Able to analyze input/output and adapt the code for similar tasks.
Theory:
1. Explain how CGI works in the context of web servers and how Python scripts can serve
dynamic content.
2. Describe what [Link]() does and how form values are retrieved safely.
3. Why must CGI scripts output the Content-Type header first? What happens if headers are
omitted?
Algorithm:
1. Start
2. Form submit
3. Read form fields via cgi
4. Generate HTML response
5. Display message
6. End
Flowchart:
Figure 14: Flowchart for Experiment 13
Code:
# Experiment 13 (CGI)
#!/usr/bin/env python3
import cgi
form = [Link]()
name = [Link]('name')
grade = [Link]('grade')
print("Content-Type: text/html\n")
print("<html><body>")
if name and grade:
print(f"<h2>Hello {name}, you have scored {grade}.</h2>")
if [Link]() == 'A':
print("<p>Excellent work!</p>")
else:
print("<p>Keep improving!</p>")
else:
print("<p>Please submit the form.</p>")
print("</body></html>")
Sample Input and Output:
CGI script outputs an HTML page with personalized message based on submitted form inputs.
Conclusion:
The program implements the stated aim and demonstrates the described concepts. Modify input
values to test other cases.
Experiment 14: Create DataFrame from NumPy array with custom column
names.
Aim:
Create DataFrame from NumPy array with custom column names.
Learning Objectives:
• Understand concepts and implementation demonstrated in this experiment.
• Practice Python programming constructs relevant to the task.
Learning Outcomes:
• Able to implement the given program in Python and understand its working.
• Able to analyze input/output and adapt the code for similar tasks.
Theory:
1. Explain how NumPy arrays and pandas DataFrames differ in terms of functionality and
typical use-cases.
2. How do you create a pandas DataFrame from a 2D NumPy array and assign custom
column names? Provide the constructor signature.
3. Describe how you would select a column, a row, and a subset (rows & columns) from the
created DataFrame. Provide examples using loc and iloc.
Algorithm:
1. Start
2. Import numpy & pandas
3. Create numpy array
4. Create DataFrame with column names
5. Display DataFrame
6. End
Flowchart:
Figure 15: Flowchart for Experiment 14
Code:
# Experiment 14
import numpy as np
import pandas as pd
arr = [Link]([[1,2,3],[4,5,6],[7,8,9]])
df = [Link](arr, columns=['Col1','Col2','Col3'])
print(df)
Sample Input and Output:
Output:
Col1 Col2 Col3
0 1 2 3
1 4 5 6
2 7 8 9
Conclusion:
The program implements the stated aim and demonstrates the described concepts. Modify input
values to test other cases.
Experiment 15: Draw a Bar Plot and Scatter Plot using Matplotlib.
Aim:
Draw a Bar Plot and Scatter Plot using Matplotlib.
Learning Objectives:
• Understand concepts and implementation demonstrated in this experiment.
• Practice Python programming constructs relevant to the task.
Learning Outcomes:
• Able to implement the given program in Python and understand its working.
• Able to analyze input/output and adapt the code for similar tasks.
Theory:
1. Explain the basic steps to create a plot in Matplotlib (figure, axes, plot, labels, show).
2. Describe the differences between [Link]() and [Link]() and typical use-cases for each.
3. How do you label axes, add a title, and include a legend in Matplotlib? Provide example
calls.
Algorithm:
1. Start
2. Import matplotlib
3. Prepare data
4. Draw bar plot
5. Draw scatter plot
6. Display plots
7. End
Flowchart:
Figure 16: Flowchart for Experiment 15
Code:
# Experiment 15
import [Link] as plt
# Bar plot
x = ['A','B','C']
y = [10, 20, 15]
[Link](figsize=(6,4))
[Link](x, y)
[Link]("Bar Plot Example")
[Link]()
# Scatter plot
x2 = [1,2,3,4,5]
y2 = [2,4,1,3,5]
[Link](figsize=(6,4))
[Link](x2, y2)
[Link]("Scatter Plot Example")
[Link]()
Sample Input and Output:
Running the code will display a bar plot and a scatter plot in separate windows/inline (if using
notebook).
Conclusion:
The program implements the stated aim and demonstrates the described concepts. Modify input
values to test other cases.