Objectives:
By the end of this course, students will be able to:
Apply building blocks of Python in solving computational problems
Explore and implement in-built data structures like Lists, Tuples, Sets, and Dictionaries.
Implement modular programming, string manipulations, and object-oriented concepts.
Develop practical contemporary applications using Functions, Modules, and Regular
Expressions.
Analyze and Debug Code: Demonstrate the ability to identify, trace, and resolve logical
and runtime errors using standard debugging techniques and exception handling.
Handle File Persistence: Perform robust Input/Output operations to read from and write
to external data sources, ensuring data persistence.
Optimize Algorithmic Logic: Evaluate and implement fundamental searching and
sorting algorithms (such as Linear Search) to improve computational efficiency.
Utilize Standard Libraries: Leverage Python’s "batteries-included" philosophy by
importing and applying built-in modules like math, date time, and collections for
specialized tasks.
Implement Best Practices: Adhere to PEP 8 styling guidelines and write self-
documenting code with meaningful variable names and doc strings to ensure
maintainability.
Apply Data Manipulation Techniques: Use advanced features like list comprehensions
and lambda functions to write concise and efficient Pythonic code.
Laboratory Rules:
Students are expected to adhere to the following guidelines to maintain a productive and safe
environment:
Do's:
Conform to the academic discipline of the department.
Enter credentials in the laboratory attendance register.
Understand the activity thoroughly before starting the experiment.
Shutdown the machine properly once work is completed.
Don'ts:
Avoid bringing eatables into the laboratory
Do not adopt generic methodologies; ensure uniqueness in experiment
execution.
Lists of Activities
Lab Activities Remark
1 Write a Python script to check if a given year is a leap year or not.
2 Write a Python script to display the reversal of a given number.
3 Write a program to find prime numbers within a given range.
4 Write a Python program to display odd numbers from 0 to 20.
5 Write a Python program to print the sum of numbers present inside a list.
6 Write a Python program to print a right-angled triangle pattern of stars.
7 Write a Python script to display elements of a list in reverse order.
8 Find the minimum and maximum elements in a list without using built-in
functions.
9 Write a Python script to remove duplicates from a list.
10 Write a Python script to create a tuple with different data types.
11 Write a Python script to add member(s) to a set.
12 Find the number of occurrences of each letter present in a given string using a
dictionary.
13 Return multiple values from a function using a return statement.
14 Implement Linear Search to find a value in a list.
15 Perform read and write operations on a file.
Activity 1: Leap Year Check
Write a Python script to check if a given year is a leap year or not.
Code
year = int(input("Enter a year: "))
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
Expected output
Enter a year: 2024
2024 is a leap year
Activity 2: Number Reversal
Write a Python script to display the reversal of a given number.
Code
num = int(input("Enter a number: "))
print("Reversed Number:", str(num)[::-1])
Expected output
Enter a number: 123
Reversed Number: 321
Activity 3: Prime Number Identification
Write a program to find prime numbers within a given range.
Code
for num in range(2, 11):
for i in range(2, num):
if (num % i) == 0:
break
else: print(num, end=' ')
Expected Output
2357
Activity 4: Display Odd Numbers
Write a Python program to display odd numbers from 0 to 20.
Code
for i in range(21):
if(i%2!=0):
print(i,end=' ')
Expected Output
1 3 5 7 9 11 13 15 17 19
Activity 5: List Summation
Write a Python program to print the sum of numbers present inside a list.
Code
list_val = eval(input("Enter List: "))
total_sum = 0
for x in list_val:
total_sum += x
print("The Sum =", total_sum)
Expected Output
Enter List: [1,4,6,7,8]
The sum = 26
Activity 5:
Code
# Define the number of rows for the triangle
rows = 5
# Outer loop for each row
for i in range(1, rows + 1):
# Inner loop for the number of stars in the current row
for j in range(i):
print("*", end=" ")
# Move to the next line after each row
print()
Expected Output
*
* *
* * *
* * * *
* * * * *
Activity 6:
Code
# Initialize the list
my_list = [10, 20, 30, 40, 50]
# Display reversed list using slicing
print("Reversed list:", my_list[::-1])
Expected Output
Reversed list: [50, 40, 30, 20, 10]
Lab 3: Find the minimum and maximum elements in a list without using built-in functions.
Code
def find_min_max(numbers):
# Handle empty list case
if not numbers:
return None, None
# Assume the first element is both the min and max
min_val = numbers[0]
max_val = numbers[0]
# Iterate through the list starting from the second element
for num in numbers[1:]:
if num > max_val:
max_val = num
elif num < min_val:
min_val = num
return min_val, max_val
# Test the function
my_list = [23, 1, 45, 99, 12, -5, 67]
minimum, maximum = find_min_max(my_list)
print(f"List: {my_list}")
print(f"Minimum: {minimum}")
print(f"Maximum: {maximum}")
Expected Output
List: [23, 1, 45, 99, 12, -5, 67]
Minimum: -5
Maximum: 99
Lab 3: Write a Python script to remove duplicates from a list.
Code
# Original list with duplicates
my_list = [1, 2, 2, 3, 4, 4, 5, 1]
# Convert to set and back to list
unique_list = list(set(my_list))
print(unique_list)
# Note: The order of elements might change
Expected Output
[1, 2, 3, 4, 5]
Lab 3: Write a Python script to create a tuple with different data types.
Code
# Creating a tuple with diverse data types
# It contains: Integer, String, Float, Boolean, and even a List
mixed_tuple = (10, "Hello Gemini", 3.14, True, [1, 2, 3])
# Display the tuple
print("The Tuple:", mixed_tuple)
# Iterate and display the type of each element
print("\nElement Details:")
for item in mixed_tuple:
print(f"Value: {item} | Type: {type(item)}")
Expected Output
The Tuple: (10, 'Hello Gemini', 3.14, True, [1, 2, 3])
Element Details:
Value: 10 | Type: <class 'int'>
Value: Hello Gemini | Type: <class 'str'>
Value: 3.14 | Type: <class 'float'>
Value: True | Type: <class 'bool'>
Value: [1, 2, 3] | Type: <class 'list'>
Lab 3: Write a Python script to add member(s) to a set.
Code
# Create an empty set
my_set = set()
# Adding a single item
my_set.add(10)
# Adding multiple items from a list
my_set.update([20, 30, 40])
# Adding items from another set
new_items = {40, 50, 60} # 40 is a duplicate and will be ignored
my_set.update(new_items)
print("Final Set:", my_set)
Expected Output
Final Set: {50, 20, 40, 10, 60, 30}
Lab 3: Find the number of occurrences of each letter present in a given string using a dictionary.
Code
def count_letters(input_string):
# Initialize an empty dictionary
frequency_dict = {}
for char in input_string:
# Check if the character is already a key in the dictionary
if char in frequency_dict:
frequency_dict[char] += 1
else:
# If it's the first time seeing the character, set count to 1
frequency_dict[char] = 1
return frequency_dict
# Test the script
text = "google"
result = count_letters(text)
print(f"String: {text}")
print("Occurrences:", result)
Expected Output
String: google
Occurrences: {'g': 2, 'o': 2, 'l': 1, 'e': 1}
Lab 3: Return multiple values from a function using a return statement.
Code
def get_user_stats():
name = "Alice"
score = 95
level = 10
return name, score, level # Returns a tuple: ("Alice", 95, 10)
# Unpacking the returned values into three variables
user_name, user_score, user_level = get_user_stats()
print(f"Name: {user_name}, Score: {user_score}, Level: {user_level}")
Expected Output
Name: Alice, Score: 95, Level: 10
Lab 3: Implement Linear Search to find a value in a list.
Code
def linear_search(data_list, target):
"""
Search for target in data_list.
Returns the index if found, otherwise returns -1.
"""
# Iterate through the list using the index
for index in range(len(data_list)):
# Check if the current element matches the target
if data_list[index] == target:
return index # Target found, return the position
return -1 # Target not found after checking the whole list
# Example usage:
numbers = [10, 50, 30, 70, 80, 60, 20, 90, 40]
search_for = 20
result = linear_search(numbers, search_for)
if result != -1:
print(f"Element {search_for} found at index: {result}")
else:
print(f"Element {search_for} not found in the list.")
Expected Output
Element 20 found at index: 6
Lab 3:
Code
# Writing to a new or existing file
content = "Hello! This is a test file.\nPython makes file handling easy."
with open("[Link]", "w") as file:
[Link](content)
print("File written successfully.")
Expected Output
Acti 16 Reading from a File
Following the file write operation, this activity focuses on retrieving data from a file using a loop
Code
# Open the previously created file in read mode
with open("[Link]", "r") as file:
# Read and print the content line by line
print("Reading file content:")
for line in file:
print([Link]())
Expected Output
Reading file content:
Hello! This is a test file.
Python makes file handling easy.
Lab 17: Counting Lines, Words, and Characters
This activity applies file handling concepts to perform basic text analysis
Code
line_count = 0
word_count = 0
char_count = 0
with open("[Link]", "r") as file:
for line in file:
line_count += 1
word_count += len([Link]())
char_count += len(line)
print(f"Lines: {line_count}")
print(f"Words: {word_count}")
print(f"Characters: {char_count}")
Expected Output
Lines: 2
Words: 10
Characters: 56
Lab 3 (Activity 18): Handling Exceptions in Python
Consistent with the goal of solving computational problems, this activity demonstrates how to handle
runtime errors during file operations.
Code
try:
with open("non_existent_file.txt", "r") as file:
data = [Link]()
except FileNotFoundError:
print("Error: The file you are trying to read does not exist.")
Expected Output
Error: The file you are trying to read does not exist.
Lab 3 (Activity 19): List Comprehension:
This activity implements in-built data structures like Lists using the efficient Pythonic "List
Comprehension" syntax.
Code
# Create a list of squares for even numbers between 1 and 10
squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print("Squares of even numbers:", squares)
Expected Output
Squares of even numbers: [4, 16, 36, 64, 100]
Lab 3 (Activity 20): Using Dictionary get() for Counting
This refines the previous dictionary activity by using the modular .get() method to handle missing
keys.
Code
text = "apple"
counts = {}
for char in text:
# get(char, 0) returns 0 if char is not in dictionary
counts[char] = [Link](char, 0) + 1
print("Character counts:", counts)
Expected Output
Character counts: {'a': 1, 'p': 2, 'l': 1, 'e': 1}