0% found this document useful (0 votes)
24 views11 pages

Py QB

The document contains a series of Python scripts demonstrating various programming concepts including functions, loops, exception handling, class inheritance, and data manipulation using libraries like NumPy and Pandas. It includes practical examples such as a currency converter, gross salary calculator, and student management system, as well as data visualization techniques using Matplotlib. Additionally, it provides instructions for running the scripts and requirements for necessary libraries.

Uploaded by

sidpradhan79
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)
24 views11 pages

Py QB

The document contains a series of Python scripts demonstrating various programming concepts including functions, loops, exception handling, class inheritance, and data manipulation using libraries like NumPy and Pandas. It includes practical examples such as a currency converter, gross salary calculator, and student management system, as well as data visualization techniques using Matplotlib. Additionally, it provides instructions for running the scripts and requirements for necessary libraries.

Uploaded by

sidpradhan79
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/ 11

# Q1) Functions, Loops, Statements, Exception Handling

# 1. Currency Converter

def rupees_to_dollar():

try:

rupees = float(input("Enter amount in Rupees: "))

dollar = rupees / 83.0

print(f"{rupees} Rupees = {dollar:.2f} Dollars")

except ValueError:

print("Invalid input!")

# 2. Gross Salary

def calculate_gross_salary():

try:

bs = float(input("Enter Basic Salary: "))

da = 0.7 * bs

ta = 0.3 * bs

hra = 0.1 * bs

gross_salary = bs + da + ta + hra

print(f"Gross Salary = INR{gross_salary:.2f}")

except ValueError:

print("Invalid input!")

# 3. Simple Interest

def simple_interest():

try:

p = float(input("Enter Principal: "))

r = float(input("Enter Rate: "))

t = float(input("Enter Time (years): "))

si = (p * r * t) / 100

print(f"Simple Interest = INR{si:.2f}")


except ValueError:

print("Invalid input!")

# 4. Arithmetic Operations

def arithmetic_operations():

try:

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

print("Addition:", a + b)

print("Subtraction:", a - b)

print("Multiplication:", a * b)

try:

print("Division:", a / b)

except ZeroDivisionError:

print("Cannot divide by zero!")

except ValueError:

print("Invalid input!")

# 5. Area Calculator

def area_calculator():

try:

print("1. Square\n2. Rectangle\n3. Triangle")

ch = int(input("Choose shape: "))

if ch == 1:

side = float(input("Enter side: "))

print("Area:", side**2)

elif ch == 2:

l = float(input("Length: "))

b = float(input("Breadth: "))

print("Area:", l * b)

elif ch == 3:
b = float(input("Base: "))

h = float(input("Height: "))

print("Area:", 0.5 * b * h)

else:

print("Invalid choice.")

except ValueError:

print("Invalid input!")

# 6. Task List

tasks = ['Go to the office', 'Pay Bills', 'Visit doctor', 'Cook the food', 'Arrange wardrobe', 'Swimming
class']

def manage_tasks():

tasks.append('New Task')

tasks[2] = 'Visit dentist'

tasks.remove('Pay Bills')

print("Tasks:", tasks)

# 7. List Operations

def list_operations():

nums = []

for _ in range(5):

nums.append(int(input("Enter number: ")))

print("List:", nums)

print("Sum:", sum(nums))

print("Max:", max(nums))

# 8. Set Operations

def set_operations():

cet = {'Alice', 'Bob', 'Carol', 'David', 'Eva'}

jee = {'Carol', 'David', 'Frank', 'George', 'Eva'}

print("Union:", cet | jee)


print("Intersection:", cet & jee)

print("Difference:", cet - jee)

# 9. Dictionary Operations

def manage_students():

students = {

"1": {"name": "Alice", "grade": 85},

"2": {"name": "Bob", "grade": 92},

"3": {"name": "Charlie", "grade": 78}

students["2"]["grade"] = 95

sorted_students = sorted(students.items(), key=lambda x: x[1]["grade"])

for k, v in sorted_students:

print(v['name'], v['grade'])

# 10. Character Check

def check_character():

ch = input("Enter a character: ")

if ch.isdigit():

print("Digit")

elif ch.islower():

print("Lowercase")

elif ch.isupper():

print("Uppercase")

else:

print("Special Character")

# 11. Multiplication Table

def multiplication_table():

try:

n = int(input("Enter number: "))


for i in range(1, 11):

print(f"{n} x {i} = {n*i}")

except ValueError:

print("Invalid input!")

# Q2: Class Inheritance, Method Overriding, Encapsulation

# Base class: Student

class Student:

def __init__(self, roll_no, name, marks):

self.__roll_no = roll_no # Encapsulated

self.__name = name # Encapsulated

self.__marks = marks # Encapsulated

def get_roll_no(self):

return self.__roll_no

def get_name(self):

return self.__name

def get_marks(self):

return self.__marks

def display(self):

print(f"Roll No: {self.__roll_no}, Name: {self.__name}, Marks: {self.__marks}")

# Task 1: Derived class Fees

class Fees(Student):

def __init__(self, roll_no, name, marks, fees):

super().__init__(roll_no, name, marks)

self.fees = fees
def submit_fees(self):

print(f"{self.get_name()} submitted INR {self.fees} as fees.")

def generate_receipt(self):

print(f"Receipt:\nStudent: {self.get_name()}, Roll No: {self.get_roll_no()}, Fees Paid: INR


{self.fees}")

# Task 2: Derived class Result

class Result(Student):

def __init__(self, roll_no, name, marks):

super().__init__(roll_no, name, marks)

self.grade = self.calculate_grade()

def calculate_grade(self):

marks = self.get_marks()

if marks >= 90:

return "A"

elif marks >= 75:

return "B"

elif marks >= 60:

return "C"

else:

return "D"

def display_result(self):

print(f"Student: {self.get_name()}, Marks: {self.get_marks()}, Grade: {self.grade}")

# Task 3: Sorting students based on marks and name

def sort_students(students):

# Sort based on marks descending, then name ascending


students.sort(key=lambda x: (-x.get_marks(), x.get_name()))

print("\n--- Sorted Students ---")

for s in students:

s.display()

# Main block to demonstrate the functionality

if __name__ == "__main__":

# Creating student objects

s1 = Fees(101, "Alice", 88, 20000)

s2 = Fees(102, "Bob", 92, 22000)

s3 = Fees(103, "Charlie", 88, 21000)

s1.display()

s1.submit_fees()

s1.generate_receipt()

print("\n--- Result Info ---")

r1 = Result(104, "David", 91)

r2 = Result(105, "Eva", 74)

r1.display_result()

r2.display_result()

# Sorting and displaying student records

student_list = [s1, s2, s3]

sort_students(student_list)

q3

Here's a complete and Python IDLE-compatible set of scripts for all tasks in Q3, including NumPy,
Pandas, and Matplotlib.

Q3.1 - NumPy Arrays and Operations


import numpy as np

# a. Create arrays

arr1D = np.array([1, 2, 3, 4, 5])

arr2D = np.array([[1, 2], [3, 4]])

arr3D = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print("1D:", arr1D)

print("2D:\n", arr2D)

print("3D:\n", arr3D)

# Reshaping

reshaped = arr1D.reshape((5, 1))

print("Reshaped 1D to 2D:\n", reshaped)

# Slicing & Indexing

print("Slice arr1D[1:4]:", arr1D[1:4])

print("arr2D[1,0]:", arr2D[1, 0])

# b. Element-wise operations

A = np.array([1, 2, 3])

B = np.array([4, 5, 6])

print("Add:", A + B)

print("Subtract:", A - B)

print("Multiply:", A * B)

print("Divide:", A / B)

# Dot and Cross product

print("Dot product:", np.dot(A, B))

print("Cross product:", np.cross(A, B))


# c. Stats operations

data = np.array([10, 20, 30, 40, 50])

print("Mean:", np.mean(data))

print("Median:", np.median(data))

print("Std Dev:", np.std(data))

print("Variance:", np.var(data))

print("Correlation:\n", np.corrcoef(data, data * 2))

Q3.2 - Pandas with Iris Dataset

Make sure you download Iris.csv from the link and save it in the same folder as this script.

import pandas as pd

# Load dataset

df = pd.read_csv("Iris.csv")

# a. First 8 rows

print("First 8 rows:\n", df.head(8))

# b. Column names

print("Column names:", df.columns.tolist())

# c. Fill missing values with mean

df.fillna(df.mean(numeric_only=True), inplace=True)

# d. Remove any rows with missing values

df.dropna(inplace=True)

# e. Group by species

grouped = df.groupby("Species")

print("Grouped by species:\n", grouped.size())


# f. Sepal Length stats

print("Sepal Length - Mean:", df["SepalLengthCm"].mean())

print("Sepal Length - Min:", df["SepalLengthCm"].min())

print("Sepal Length - Max:", df["SepalLengthCm"].max())

Q3.3 - Matplotlib with Cars Dataset

Make sure you download Toyota.csv from the link and save it in the same folder as this script.

import pandas as pd

import matplotlib.pyplot as plt

# Load dataset

df = pd.read_csv("Toyota.csv")

# a. Scatter Plot: Age vs Price

plt.scatter(df['Age'], df['Price'], color='blue')

plt.title("Price vs Age")

plt.xlabel("Age")

plt.ylabel("Price")

plt.grid(True)

plt.show()

# b. Histogram: KM Driven

plt.hist(df['KM'], bins=10, color='green')

plt.title("KM Driven Distribution")

plt.xlabel("Kilometers Driven")

plt.ylabel("Frequency")

plt.show()

# c. Bar Plot: Fuel Type

fuel_counts = df['FuelType'].value_counts()
fuel_counts.plot(kind='bar', color='orange')

plt.title("Car Count by Fuel Type")

plt.xlabel("Fuel Type")

plt.ylabel("Number of Cars")

plt.show()

# d. Pie Chart: Fuel Type

fuel_counts.plot(kind='pie', autopct='%1.1f%%')

plt.title("Fuel Type Distribution")

plt.ylabel("")

plt.show()

# e. Box Plot: Price across Fuel Types

df.boxplot(column='Price', by='FuelType')

plt.title("Price Distribution by Fuel Type")

plt.suptitle("") # Removes the automatic title

plt.xlabel("Fuel Type")

plt.ylabel("Price")

plt.show()

How to Run:

1. Download required CSV files:

o Iris.csv from Kaggle (for Pandas part).

o Toyota.csv from Kaggle (for Matplotlib part).

2. Save these scripts as .py files and run them using F5 in Python IDLE.

3. Make sure you have the required libraries installed:

4. pip install numpy pandas matplotlib

Want me to combine all this into a single .py or .pdf file?

You might also like