0% found this document useful (0 votes)
0 views14 pages

Varnitjain 2300290120277 Cs3d Pythonassignment02

The document contains a series of Python lab assignments that cover various programming tasks, including file handling, data processing, and user interaction. Each task demonstrates different functionalities such as calculating averages, counting words, managing inventory, and implementing a simple alarm system. The assignments also include operations like encryption, banking transactions, employee management, and data visualization using libraries like pandas and matplotlib.

Uploaded by

thepsyforge
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)
0 views14 pages

Varnitjain 2300290120277 Cs3d Pythonassignment02

The document contains a series of Python lab assignments that cover various programming tasks, including file handling, data processing, and user interaction. Each task demonstrates different functionalities such as calculating averages, counting words, managing inventory, and implementing a simple alarm system. The assignments also include operations like encryption, banking transactions, employee management, and data visualization using libraries like pandas and matplotlib.

Uploaded by

thepsyforge
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/ 14

VARNIT JAIN

2300290120277
CS3D
PYTHON LAB ASSIGNMENT 02

1)

with open('org.txt', 'r') as file:


students = []
grades = []

for line in file:


name, grade = line.strip().split(',')
students.append(name)
grades.append(float(grade))

average = sum(grades) / len(grades) if grades else 0


with open('cpy.txt', 'w') as file:
for name, grade in zip(students, grades):
file.write(f"{name}: {grade}\n")
file.write(f"Average grade: {average:.2f}\n")

2)

import string

with open('org.txt', 'r') as file:


text = file.read()

text = text.translate(str.maketrans('', '', string.punctuation)).lower()


words = text.split()

word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1

with open('cpy.txt', 'w') as file:


for word, count in word_counts.items():
file.write(f"{word}: {count}\n")

3)
library_catalog = {}

with open('org.txt', 'r') as file:


for line in file:
title, author = line.strip().split(',')
library_catalog[title] = author

with open('cpy.txt', 'w') as file:


for title, author in library_catalog.items():
file.write(f"Book: {title}, Author: {author}\n")

search_title = "1984"
if search_title in library_catalog:
print(f"Book: {search_title}, Author: {library_catalog[search_title]}")
else:
print("Book not found.")

4)

tasks = []

with open('org.txt', 'r') as file:


for line in file:
tasks.append(line.strip())
new_task = "Finish Python project"
tasks.append(new_task)

with open('cpy.txt', 'w') as file:


for task in tasks:
file.write(f"{task}\n")

print("To-Do List:")
for idx, task in enumerate(tasks, 1):
print(f"{idx}. {task}")

5)

inventory = {}

with open('org.txt', 'r') as file:


for line in file:
product, quantity, supplier = line.strip().split(',')
inventory[product] = {'quantity': int(quantity), 'supplier': supplier}

new_product = "Laptop"
new_quantity = 50
new_supplier = "TechSupplier Inc."
inventory[new_product] = {'quantity': new_quantity, 'supplier': new_supplier}
with open('cpy.txt', 'w') as file:
for product, details in inventory.items():
file.write(f"{product},{details['quantity']},{details['supplier']}\n")

print("Inventory List:")
for product, details in inventory.items():
print(f"Product: {product}, Quantity: {details['quantity']}, Supplier: {details['supplier']}")

6)

import requests

url = "https://api.exchangerate-api.com/v4/latest/USD"
response = requests.get(url)
data = response.json()

print("Available Currencies: ", data['rates'].keys())

from_currency = input("Enter the currency to convert from (e.g., USD): ").upper()


to_currency = input("Enter the currency to convert to (e.g., EUR): ").upper()
amount = float(input(f"Enter amount in {from_currency}: "))
if from_currency == "USD":
converted_amount = amount * data['rates'].get(to_currency, 0)
elif to_currency == "USD":
converted_amount = amount / data['rates'].get(from_currency, 1)
else:
converted_amount = amount * data['rates'].get(to_currency, 0) / data['rates'].get(from_currency, 1)

print(f"{amount} {from_currency} = {converted_amount:.2f} {to_currency}")

7)

import time
import threading
from datetime import datetime

while True:
current_time = datetime.now().strftime("%H:%M:%S")
print(f"Current Time: {current_time}", end='\r')
time.sleep(1)

alarm_time = input("Enter alarm time in HH:MM:SS format or press Enter to skip: ")
if alarm_time:
while True:
current_time = datetime.now().strftime("%H:%M:%S")
print(f"Current Time: {current_time}", end='\r')
time.sleep(1)
if current_time == alarm_time:
print(f"Alarm! It's {alarm_time}!")
break

8)

import math

while True:
op = input("\n1. + 2. - 3. * 4. / 5. sqrt 6. ! 7. Exit\nChoose operation: ")

if op == "1":
num1, num2 = input("Enter two numbers: ").split()
print(float(num1) + float(num2))
elif op == "2":
num1, num2 = input("Enter two numbers: ").split()
print(float(num1) - float(num2))
elif op == "3":
num1, num2 = input("Enter two numbers: ").split()
print(float(num1) * float(num2))
elif op == "4":
num1, num2 = input("Enter two numbers: ").split()
print(float(num1) / float(num2) if float(num2) != 0 else "Error")
elif op == "5":
num = float(input("Enter number: "))
print(math.sqrt(num) if num >= 0 else "Error")
elif op == "6":
num = int(input("Enter integer: "))
print(math.factorial(num) if num >= 0 else "Error")
elif op == "7":
break
else:
print("Invalid")

10)

while True:
print("\n1. Encrypt")
print("2. Decrypt")
print("3. Exit")

choice = input("Choose option: ")

if choice == '1':
message = input("Enter message: ")
key = int(input("Enter key: "))
encrypted = ''.join([chr((ord(c) + key - 32) % 95 + 32) for c in message])
print(f"Encrypted: {encrypted}")

elif choice == '2':


message = input("Enter message: ")
key = int(input("Enter key: "))
decrypted = ''.join([chr((ord(c) - key - 32) % 95 + 32) for c in message])
print(f"Decrypted: {decrypted}")

elif choice == '3':


break
else:
print("Invalid choice.")

11)

balance = 0

while True:
print("\n1. Deposit")
print("2. Withdraw")
print("3. Check Balance")
print("4. Exit")

choice = input("Choose an option: ")

if choice == '1':
amount = float(input("Enter deposit amount: "))
balance += amount
print(f"Deposited: {amount}")

elif choice == '2':


amount = float(input("Enter withdrawal amount: "))
if amount <= balance:
balance -= amount
print(f"Withdrawn: {amount}")
else:
print("Insufficient funds.")
elif choice == '3':
print(f"Current Balance: {balance}")

elif choice == '4':


break
else:
print("Invalid choice.")

12)

employees = []

while True:
print("\n1. Add Employee")
print("2. View Employees")
print("3. Exit")

choice = input("Choose an option: ")

if choice == '1':
name = input("Enter employee name: ")
emp_id = input("Enter employee ID: ")
salary = float(input("Enter salary: "))
employees.append({"Name": name, "ID": emp_id, "Salary": salary})
print("Employee added.")

elif choice == '2':


if employees:
print("\nEmployee Details:")
for emp in employees:
print(f"Name: {emp['Name']}, ID: {emp['ID']}, Salary: {emp['Salary']}")
else:
print("No employees found.")

elif choice == '3':


break
else:
print("Invalid option.")

13)

import pandas as pd

data = None

while True:
print("\n1. Load CSV 2. Filter 3. Sort 4. Handle Missing 5. Exit")
choice = input("Choose an option: ")

if choice == '1':
data = pd.read_csv(input("Enter CSV file path: "))
print(data)
elif choice == '2' and data is not None:
col, val = input("Enter column and value to filter: ").split()
print(data[data[col] == val])
elif choice == '3' and data is not None:
col = input("Enter column to sort: ")
print(data.sort_values(by=col))
elif choice == '4' and data is not None:
print(data.fillna("N/A"))
elif choice == '5':
break
else:
print("Invalid or no data loaded.")

14)

import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv(input("Enter CSV file path: "))

print("\nPlot Types: Line, Bar, Scatter, Histogram")


plot_type = input("Choose plot type: ")
x_col = input("Enter x-axis column: ")
y_col = input("Enter y-axis column: ")
title = input("Enter plot title: ")
color = input("Enter plot color: ")

plt.figure()

if plot_type == "Line":
plt.plot(data[x_col], data[y_col], color=color)
elif plot_type == "Bar":
plt.bar(data[x_col], data[y_col], color=color)
elif plot_type == "Scatter":
plt.scatter(data[x_col], data[y_col], color=color)
elif plot_type == "Histogram":
plt.hist(data[y_col], bins=10, color=color)

plt.title(title)
plt.xlabel(x_col)
plt.ylabel(y_col)
plt.legend([plot_type])
plt.show()

15)

import numpy as np
import matplotlib.pyplot as plt

# Ask user for input function


func = input("Enter a mathematical function (e.g., np.sin(x), np.cos(x), np.exp(x)): ")

# Generate the x values


x = np.linspace(-10, 10, 400)

# Try to evaluate the function entered by the user


try:
y = eval(func)
plt.plot(x, y, label=func)
plt.title(f"Plot of {func}")
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()
except Exception as e:
print(f"Error: {e}")

You might also like