Aim : Create a program that uses a graphical user interface (GUl) to allow the user to
perform simple calculations.
Code:
import tkinter as tk
from tkinter import messagebox
def calculate():
try:
num1 = float([Link]())
num2 = float([Link]())
operator = operator_var.get()
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
result = num1 / num2
result_label.config(text="Result: " + str(result))
except ZeroDivisionError:
[Link]("Error", "Division by zero is not allowed")
except ValueError:
[Link]("Error", "Please enter valid numbers")
root = [Link]()
[Link]("Simple Calculator")
[Link]("300x250")
[Link](root, text="Enter First Number").pack()
entry1 = [Link](root)
[Link]()
[Link](root, text="Enter Second Number").pack()
entry2 = [Link](root)
[Link]()
operator_var = [Link](value="+")
[Link](root, operator_var, "+", "-", "*", "/").pack()
[Link](root, text="Calculate", command=calculate).pack()
result_label = [Link](root, text="Result: ")
result_label.pack()
[Link]()
Output:
Aim : Create a program that uses a web scraping library to extract data from a website and
then stores it in a database.
Code:
import requests
from bs4 import BeautifulSoup
import sqlite3
url = "[Link]
response = [Link](url)
soup = BeautifulSoup([Link], "[Link]")
conn = [Link]("[Link]")
cursor = [Link]()
[Link]("""
CREATE TABLE IF NOT EXISTS quotes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
quote TEXT,
author TEXT
)
""")
quotes = soup.find_all("span", class_="text")
authors = soup.find_all("small", class_="author")
for quote, author in zip(quotes, authors):
[Link]("INSERT INTO quotes (quote, author) VALUES (?, ?)",
([Link], [Link]))
[Link]()
[Link]()
print("Data scraped and stored in database successfully.")
Output:
Aim : Create a program that reads data from a file and then creates a visualization of that data
using a data visualization library.
Code:
import csv
with open("[Link]", "w", newline="") as file:
writer = [Link](file)
[Link](["Month", "Sales"])
[Link](["Jan", 200])
[Link](["Feb", 350])
[Link](["Mar", 300])
[Link](["Apr", 400])
[Link](["May", 450])
print("[Link] created successfully.")
%matplotlib inline
import csv
import [Link] as plt
months = []
sales = []
with open("[Link]", "r") as file:
reader = [Link](file)
next(reader)
for row in reader:
[Link](row[0])
[Link](int(row[1]))
[Link](months, sales)
[Link]("Monthly Sales Data")
[Link]("Month")
[Link]("Sales")
[Link]()
Output:
Aim: Create a program that uses a machine learning library to classify images based on their
content.
Code:
# Image Classification using TensorFlow and Keras (Pretrained Model)
import tensorflow as tf
from [Link].mobilenet_v2 import (
MobileNetV2,
preprocess_input,
decode_predictions
)
from [Link] import image
import numpy as np
# Load pre-trained MobileNetV2 model
model = MobileNetV2(weights="imagenet")
# Load and prepare the image
img_path = "[Link]" # Provide your image file here
img = image.load_img(img_path, target_size=(224, 224))
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array = preprocess_input(img_array)
# Predict
predictions = [Link](img_array)# Decode predictions
results = decode_predictions(predictions, top=3)[0]
print("Top Predictions:")
for i, (imagenetID, label, probability) in enumerate(results):
print(f"{i+1}. {label} - {probability*100:.2f}%")
Output:
Aim: Create a program that uses a networking library to communicate with a server and
retrieve data from it.
Code:
import requests
def fetch_server_data(post_id):
# The URL of the server endpoint
url = f"[Link]
try:
# 1. Send the GET request to the server
response = [Link](url, timeout=5)
# 2. Check if the request was successful (Status Code 200)
# This raises an exception for 4xx or 5xx errors
response.raise_for_status()
# 3. Parse the data as JSON (dictionaries/lists in Python)
data = [Link]()
print(f"--- Connection Successful ---")
print(f"Title: {data['title']}")
print(f"Body: {data['body']}")
except [Link] as http_err:
print(f"HTTP error occurred: {http_err}")
except [Link]:print("Error: Could not connect to
the server. Check your internet.")
except Exception as err:
print(f"An unexpected error occurred: {err}")
# Execute the function
if name == " main ":
fetch_server_data(1)
Output: