My Document
My Document
Ex No: 1 Date of
Completion Additional Credits
Create a class Car with attributes like brand, model, and year
AIM:
Write a python program to create A class Car with attributes like brand ,model, and
year. Then create an object of this class and display it’s attribute.
ALGORITHM:
Step1: Start
Step2: Define a class named Car.
Step3: Create a constructor (_init_) to initialize attributes.
Step4: Assign values to the attributes using self.
Step5: Create an object of the Car class and pass values.
Step6: Print the car details using f-string.
Step7: Stop
PROGRAM:
class Car:
def __init__(self, brand, model, year):
def self.brand = brand
self.model = model
self.year = year
My_car = Car(“Toyota”,”Corolla”, 2020)
print(f”Brand:{my_car.brand},Model:{my_car.
model}, Year:{my_car.year}”)
OUTPUT:
1
Experiment Score /10
Ex No: 2 Date of
Completion Additional Credits
AIM:
Define a class Employee with private attributes like name and salary. Provide
methods to get and set these attributes. Access the attributes through these methods.
ALGORITHM:
Step1: Start
Step2: Define a class named Employee.
Step3: Create a constructor (_init_) to initialize the private attributes.
Step4: Define getter methods to retrieve the values of private attributes.
Step5: Define setter methods to update the private attributes.
Step6: Create an object of the Employee class and pass values.
Step7: Call getter methods to display the employee’s name and salary.
Step8: Stop
PROGRAM:
class Employee:
def __init__ (self, name, salary):
self. name = name
self. __salary = salary
def get_name(self):
return self. __name
def set_name(self, name):
self. __name = name
def get_salary(self):
return self. __salary
def set_salary(self, salary):
self. __salary = salary
emp = Employee("John", 50000)
print(emp.get_name(), emp.get_salary())
OUTPUT:
John 50000
2
Experiment Score /10
Ex No: 3 Date of
Completion Additional Credits
Create a base class Animal with derived classes Dog and Cat.
AIM:
Create a base class Animal with a method sound(). Create derived classes Dog
and Cat, each overriding the sound() method to make a specific sound.
ALGORITHM:
Step1: Start
Step2: Define a base class Animal : Create a method sound() that will be overridden
by derived classes
Step3: Create a derived class Dog that inherits from Animal.
Step4: Create another derived class Cat that also inherits from Animal
Step5: Create objects of Dog and Cat.
Step6: Call the sound() method for both objects and print the results.
Step7: Stop
PROGRAM:
class Animal:
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Woof!"
class Cat(Animal):
def sound(self):
return "Meow!"
dog = Dog()
cat = Cat()
print(dog.sound(), cat.sound())
OUTPUT:
Woof! Meow!
3
Experiment Score /10
Ex No: 4 Date of
Completion Additional Credits
ALGORITHM:
Step 1: Start
Step 2: Define a class Book.
Step 3: Initialize attributes (title and author) in the _init_ method.
Step 4: Implement the _str_() method.
Step 5: Create an object of the Book class with sample data.
Step 6: Print the object, which will automatically call the _str_() method.
Step 7: Stop
PROGRAM:
class Book:
def __init__ (self, title, author):
self.title = title
self.author = author
def __str__ (self):
return f"{self.title} by {self.author}"
book = Book("1984", "George Orwell")
print(book)
OUTPUT:
4
Experiment Score /10
Ex No: 5 Date of
Completion Additional Credits
AIM:
ALGORITHM:
Step 1: Start
Step 2: Define a custom exception class InvalidAgeError that inherits
from Exception.
Step 3: Create a function check age(age):
If age is less than 0 or greater than 120, raise an
InvalidAgeError with a custom message:
Step 4: Use a try-except block:Call check_age(130).
Step 5 : Catch the InvalidAgeError and print the error message.
Step 6: Stop
PROGRAM:
class InvalidAgeError(Exception):
pass
def check_age(age):
if age < 0 or age > 120:
raise InvalidAgeError("Age must be between 0 and 120")
try:
check_age(130)
except InvalidAgeError as e:
print(e)
OUTPUT:
5
Experiment Score /10
Ex No: 6 Date of
Completion Additional Credits
AIM:
Create a generator that yields Fibonacci numbers up to a specified limit. Use this
generator to print the first n Fibonacci numbers.
ALGORITHM:
Step 1: Start
Step 2: 1. Define a generator function fibonacci(limit):Initialize a = 0 and b = 1 (first
two Fibonacci numbers).
Step 3: Use a for loop to iterate over the Fibonacci generator .
Step 4: And print each number.
Step 5: Stop
PROGRAM:
def fibonacci(limit):
a, b = 0, 1
while a < limit:
yield a
a , b = b, a + b
for num in fibonacci(100):
print(num)
OUTPUT:
0 1 1 2 3 5 8 13 21 34 55 89
6
Experiment Score /10
Ex No: 7 Date of
Completion Additional Credits
AIM:
ALGORITHM:
Step 1: Start
Step 2: Import the time module to measure execution time.
Step 3: Define a decorator function timer(func):
Step 4: Use @timer decorator to apply it to the factorial function.
Step 5: Define a recursive factorial(n) function to calculate the factorial of n.
Step 6: Call factorial(5) and print the result along with execution time.
Step 7: Stop
PROGRAM:
import time
def timer(func):
start = time.time()
end = time.time()
return wrapper
7
@timer
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
OUTPUT:
120
8
Experiment Score /10
Ex No:
Ex No: 89 Date of
Completion Additional Credits
AIM:
Write a Python program to store a list of dictionaries using pickle, and then
load and display the stored object.
ALGORITHM:
Step 1: Start
PROGRAM:
import pickle
data = [{'name': 'John', 'age': 30}, {'name': 'Jane', 'age': 25}]
OUTPUT:
11
Experiment Score /10
Ex No:9
Ex No:10 Date of
Completion Additional Credits
Read a large text file line by line and print lines containing a keyword
AIM:
Write a program that reads a large text file line by line and prints only lines that
contain specific keyword.
ALGORITHM:
Step 1: Start
Step 2: Define a keyword to search for in the text file.
Step 3: Open the file (large_file.txt) in read (r) mode using with
open(...) to handle it safely.
Step 4: Iterate through each line of the file using a for loop.
Step 5: Check if the keyword exists in the current line.
Step 6: If the keyword is found, print the line.
Step 7: Close the file automatically after reading (handled by with open(...)).
Step 8: Stop
PROGRAM:
keyword = "Python"
with open('large_file.txt', 'r') as file:
for line in file:
if keyword in line:
print(line)
OUTPUT :
12
Experiment Score /10
Ex No:11 Date of
Ex No:10 Completion Additional Credits
AIM:
Use sqlite3 to create a database, a table, and perform basic CRUD (Create,
Read, Update, Delete) operations.
ALGORITHM :
Step 1: Start
13
Step 7: Delete a Record
Step7.1: Execute a DELETE FROM users query to remove John
from the table.
Step 8: Commit Changes and Close Connection
Step8.1: Call conn.commit() to save the changes.
Step8.2: Close the database connection using conn.close().
Step 9: Stop
PROGRAM:
import sqlite3
conn = sqlite3.connect('example.db’)
c = conn.cursor()
# Create table
c.execute('''CREATE TABLE IF NOT EXISTS
users (id INTEGER PRIMARY KEY, name TEXT, age
INTEGER)'‘’)
# Insert
c.execute("INSERT INTO users (name, age)
VALUES ('John', 30)")
# Read
c.execute("SELECT * FROM users")
print(c.fetchall())
# Update
c.execute("UPDATE users SET age = 31
WHERE name = 'John’”)
# Delete
c.execute("DELETE FROM users WHERE
name = 'John’”)
conn.commit()
conn.close()
OUTPUT:
[(1, 'John', 30)]
14
Experiment Score /10
Ex No:12
Ex No:11 Date of
Completion Additional Credits
AIM:
Build a simple Flask app that displays "Hello, World!" when accessed at the root
URL (/).
ALGORITHM :
Step 1: Start
Step 2: Import Required Module
Step2.1: Import Flask from the flask package.
@app.route('/’)
def hello_world():
return 'Hello, World!’
OUTPUT:
Running the app displays "Hello, World!" at the root endpoint.
15
Experiment Score /10
Ex No:13
Ex No:12 Date of
Completion Additional Credits
AIM:
Write a Flask app with multiple routes and use Jinja2 templates to
display dynamic content, like a user's name
ALGORITHM :
Step 1: Start
Step5.1: Ensure the app runs only when executed directly using if
_name_ == '_main_’:.
Step 6: Stop
16
PROGRAM:
from flask import Flask, render_template
app = Flask( name )
@app.route('/’)
def home():
return render_template('home.html’)
@app.route('/user/<name>’)
def user(name):
return render_template('user.html', name=name)
OUTPUT:
Renders templates for the home page and a dynamic user page.
17
Experiment Score /10
Ex No:14
Ex No:13 Date of Completion Additional Credits
AIM:
Build a simple Flask REST API that handles GET and POST requests, such as
managing a list of tasks.
ALGORITHM :
Step 1: Start
GET /tasks
Returns all tasks in JSON format using jsonify(tasks).
POST /tasks
Reads JSON data from request.json.
Appends the new task to the tasks list.
Returns the added task with status code 201.
Step 6: Stop
18
PROGRAM:
tasks = []
@app.route('/tasks', methods=['GET’])
def get_tasks():
return jsonify(tasks)
@app.route('/tasks', methods=['POST’])
def add_task():
task = request.json
tasks.append(task)
return jsonify(task), 201
OUTPUT:
19
Experiment Score /10
Ex No:
Ex No: 14
17 Date of
Completion Additional Credits
AIM:
Write unit tests for a Python function that calculates the factorial of a
number using the unittest module.
ALGORITHM :
Step 1: Start
Step 2: Import Required Modules
Step2.1: Import unittest for writing test cases.
Step 3: Define the Factorial Function
Step3.1: Implement a recursive function factorial(n):
Base case: If n == 0, return 1.
Recursive case: Multiply n by factorial(n - 1).
Step 4: Write Unit Tests
Step4.1: Create a test class TestFactorial that inherits from
unittest.TestCase.
Step4.2: Define multiple test cases inside the class using
self.assertEqual().
Step 5: Run Unit Tests
Step5.1: Use unittest.main() inside if _name_ == '_main_': to
execute the tests when the script runs.
Step 6: Stop
PROGRAM:
import unittest
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
class TestFactorial(unittest.TestCase):
def test_factorial(self):
self.assertEqual(factorial(5), 120)
if __name__ == ‘__main__ ‘:
unittest.main()
Output:
----------------------------------------------------------------------
Ran 1 test in<some seconds>
OK
23
Experiment Score /10
Ex No:
Ex No: 15
18 Date of
Completion Additional Credits
Aim:
Implement logging in your Python program to track errors. Use pdb to
debug and set breakpoints in the code.
ALGORITHM :
Step 1: Start
Step 2: Import Required Modules
Step2.1: Import logging for logging messages.
Step2.2: Import pdb for debugging.
Step 3: Configure Logging
Step3.1: Use logging.basicConfig(level=logging.DEBUG) to set the
logging level to DEBUG.
Step 4: Define a Function with a Bug
Step4.1: Define buggy_function() containing an intentional
bug (1 + '1’).
Step4.2: Insert pdb.set_trace() before the bug to start the
debugger.
Step 5: Log Debug Messages
Step5.1: Use logging.debug('Starting the function') before calling
buggy_function().
Step 6: Run the Function and Debug
Step6.1: Execute buggy_function(), which triggers pdb debugging
before the error occurs.
Step 7: Stop
PROGRAM:
import logging
import pdb
logging.basicConfig(level=logging.DEBUG)
def buggy_function():
pdb.set_trace() result = 1 + '1’ # Intentional bug
return result
24
Experiment Score /10
Ex No:
Ex No: 16
19 Date of
Completion Additional Credits
Aim:
Use Python's threading module to download multiple files concurrently
from different URLs.
ALGORITHM :
Step 1: Start
Step 2: Import Required Modules
Step2.1: Import threading for multi-threading.
Step2.2: Import requests to download files.
Step 3: Define a Function to Download a File
Step3.1: Send a GET request to the url.
Step3.2: Save the response content to a local file (filename).
Step 4: Define URLs to Download
Step4.1: Create a list of file URLs (urls).
Step 5: Create and Start Threads
Step5.1: Loop through urls and create a Thread for each file.
Step5.2: Start the thread immediately after creating it.
Step 6: Wait for Threads to Complete
Step6.1: Use thread.join() to ensure all downloads finish before
proceeding.
Step 7: Stop
PROGRAM:
import threading
import requests
25
for url in urls:
thread = threading.Thread(target=download_file, args=(url, url.split('/')[-1]))
threads.append(thread)
thread.start()
OUTPUT:
26