0% found this document useful (0 votes)
4 views21 pages

My Document

The document outlines a series of programming experiments in Python, covering various concepts such as class creation, exception handling, decorators, file handling, and Flask web development. Each experiment includes an aim, algorithm, program code, and expected output. The experiments are designed to enhance understanding of Python programming and its applications.

Uploaded by

raman4005kvr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views21 pages

My Document

The document outlines a series of programming experiments in Python, covering various concepts such as class creation, exception handling, decorators, file handling, and Flask web development. Each experiment includes an aim, algorithm, program code, and expected output. The experiments are designed to enhance understanding of Python programming and its applications.

Uploaded by

raman4005kvr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Experiment Score /10

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:

Brand: Toyota, Model: Corolla, Year: 2020

1
Experiment Score /10
Ex No: 2 Date of
Completion Additional Credits

. Define a class Employee with private attributes

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

Implement the__str__() method in a


class.
AIM:

Implement the __str__() method in a class to return a human-readable string


representing the class instance.

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:

1984 by George Orwell

4
Experiment Score /10
Ex No: 5 Date of
Completion Additional Credits

Define a custom exception InvalidAgeError.

AIM:

Define a custom exception InvalidAgeError and raise it if an age input is


less than 0 or greater than 120.

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:

Age must be between 0 and 120

5
Experiment Score /10
Ex No: 6 Date of
Completion Additional Credits

Create a generator that yields Fibonacci numbers.

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

Create a decorator that measures execution time

AIM:

Create a decorator that measures the execution time of a function. Apply it to a


function that calculates a large factorial.

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):

def wrapper(*args, **kwargs):

start = time.time()

result = func(*args, **kwargs)

end = time.time()

print(f"Time taken: {end - start} seconds")


return result

return wrapper

7
@timer

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n - 1)

print(factorial(5))

OUTPUT:

120

Time taken : seconds

8
Experiment Score /10
Ex No:
Ex No: 89 Date of
Completion Additional Credits

Store and load a list of dictionaries using pickle.

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

Step 2: Import the pickle module to enable serialization and


deserialization.
Step 3: Create a list of dictionaries containing key-value pairs (name and age).
Step 4: Open a file (data.pkl) in write-binary (wb) mode to store the
data.Use pickle.dump(data, file) to serialize and save the list into the file.
Step 5: Open the same file (data.pkl) in read-binary (rb) mode to load the
data.Use pickle.load(file) to deserialize and retrieve the stored data.
Step 6 : Print the loaded data to verify that it matches the original list.
Step 7: Stop

PROGRAM:

import pickle
data = [{'name': 'John', 'age': 30}, {'name': 'Jane', 'age': 25}]

with open('data.pkl', 'wb') as file:


pickle.dump(data, file)

with open('data.pkl', 'rb') as file:


loaded_data = pickle.load(file)
print(loaded_data)

OUTPUT:

[{'name': 'John', 'age': 30}, {'name': 'Jane', 'age': 25}]

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 :

Prints lines containing the keyword "Python"

12
Experiment Score /10
Ex No:11 Date of
Ex No:10 Completion Additional Credits

Use sqlite3 to perform CRUD operations.

AIM:
Use sqlite3 to create a database, a table, and perform basic CRUD (Create,
Read, Update, Delete) operations.

ALGORITHM :

Step 1: Start

Step 2: Connect to the SQLite Database.

Step2.1: Import sqlite3

Step3.2: Establish a connection to example.db.

Step2.3: Create a cursor object to execute SQL queries.

Step 3: Create a Table (users)

Step3.1: Execute a CREATE TABLESQL command with


columns:id (Primary Key, Auto-incremented Integer)name (Text)age (Integer)

Step3.2: Use IF NOT EXISTS to prevent duplicate table


creation.

Step 4: Insert a New Record.

Step4.1: Execute an INSERT INTO statement to add a new user


(John, 30).

Step 5: Read and Display Records.

Step5.1: Execute a SELECT * FROM users query.

Step5.2: Use fetchall() to retrieve all results.

Step 6: Update a Record

Step6.1: Execute an UPDATE query to modify John’s age from


30 to 31.

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

Build a simple Flask app.

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.

Step 3: Create a Flask Application Instance


Step3.1: Initialize a Flask app using Flask(_name_).
Step 4: Define a Route and View Function
Step4.1: Use @app.route('/') to define the homepage (/).
Step4.2: Create a function (hello_world()) that returns a
response ('Hello, World!’).
Step 5: Run the Flask Application
Step5.1: Use if _name_ == '_main_': to ensure the app runs only
when executed directly.
Step5.2:Call app.run() to start the Flask development server.
Step 6: Stop
PROGRAM:

from flask import Flask


app = Flask(__name__)

@app.route('/’)
def hello_world():
return 'Hello, World!’

if __name__ == ‘__ main__ ‘:


app.run()

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

Write a Flask app with multiple routes and Jinja2 templates.

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

Step 2: Import Required Modules

Step2.1:Import Flask and render_template from flask.

Step 3: Create a Flask App Instance

Step3.1: Initialize a Flask application using Flask(__name__).

Step 4: Define Routes and View Functions

Step4.1: Home Route (/)


Uses @app.route('/’).
Returns home.html using render_template().

Step4.2: User Route (/user/<name>)


Uses @app.route('/user/<name>’).
Passes name as a variable to user.html.

Step 5: Run the Flask Application

Step5.1: Ensure the app runs only when executed directly using if
_name_ == '_main_’:.

Step5.2: Call app.run(debug=True) to start the Flask development


server with debugging enabled.

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)

if __name__ == ‘__ main__ ‘:


app.run()

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

Build a simple Flask REST API.

AIM:
Build a simple Flask REST API that handles GET and POST requests, such as
managing a list of tasks.

ALGORITHM :

Step 1: Start

Step 2: Import Required Modules

Step2.1:Import Flask, jsonify, and request from flask.

Step 3: Create a Flask App Instance

Step3.1: Initialize a Flask application using Flask(_name_).

Step3.2: Define an empty list tasks to store task data.

Step 4: Define API Endpoints

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 5: Run the Flask Application

Step5.1: Ensure the app runs only when executed directly


using if _name_ == '_main_’:.

Step5.2: Call app.run(debug=True) to start the Flask


development server with debugging enabled.

Step 6: Stop

18
PROGRAM:

from flask import Flask, jsonify, request


app = Flask(__name__)

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

if __name __==‘ __main__ ‘:


app.run()

OUTPUT:

Provides GET and POST endpoints for managing tasks

19
Experiment Score /10
Ex No:
Ex No: 14
17 Date of
Completion Additional Credits

Write unit tests for a factorial function.

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

Implement logging and use pdb for debugging

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

logging.debug('Starting the function’)


buggy_function()
Output:

Triggers a breakpoint and a TypeError.

24
Experiment Score /10
Ex No:
Ex No: 16
19 Date of
Completion Additional Credits

Use Python's threading module to download files concurrently.

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

def download_file(url, filename):


response = requests.get(url)
with open(filename, 'wb') as file:
file.write(response.content)

urls = ['http://example.com/file1', 'http://example.com/file2’]


threads = []

25
for url in urls:
thread = threading.Thread(target=download_file, args=(url, url.split('/')[-1]))
threads.append(thread)
thread.start()

for thread in threads:


thread.join()

OUTPUT:

Downloads files concurrently and saves them locally

26

You might also like