0% found this document useful (0 votes)
1 views8 pages

Python Programs

The document contains a series of Python programming exercises that cover various topics such as arithmetic operations, percentage calculation, simple and compound interest, rectangle perimeter, BMI calculation, currency conversion, and data manipulation using Pandas and NumPy. It also includes tasks for creating plots with Matplotlib and saving data in CSV format. Additionally, it provides guidance on saving the code in Jupyter Notebook or as a Python script.

Uploaded by

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

Python Programs

The document contains a series of Python programming exercises that cover various topics such as arithmetic operations, percentage calculation, simple and compound interest, rectangle perimeter, BMI calculation, currency conversion, and data manipulation using Pandas and NumPy. It also includes tasks for creating plots with Matplotlib and saving data in CSV format. Additionally, it provides guidance on saving the code in Jupyter Notebook or as a Python script.

Uploaded by

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

Python Programs

Q1. Write a program to input two numbers from the user and display their:
- Sum
- Difference
- Product
- Quotient
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

print("Sum:", a + b)
print("Difference:", a - b)
print("Product:", a * b)
if b != 0:
print("Quotient:", a / b)
else:
print("Cannot divide by zero.")

Q2. A student scored 480 marks out of 600. Write a program to calculate and
print the percentage.
marks_obtained = 480
total_marks = 600
percentage = (marks_obtained / total_marks) * 100
print("Percentage:", percentage, "%")

Q3. A shirt is priced at ₹800. There’s a 20% discount on it. Calculate the amount
saved and final price.
price = 800
discount = 20 # percent
amount_saved = (discount / 100) * price
final_price = price - amount_saved

print("Amount Saved: ₹", amount_saved)


print("Final Price: ₹", final_price)

Q4. Write a program to calculate Simple Interest using the formula:


SI = (P × R × T) / 100
where P = ₹5000, R = 8%, and T = 2 years.
P = 5000 # Principal
R = 8 # Rate
T = 2 # Time
SI = (P * R * T) / 100
print("Simple Interest: ₹", SI)
Q5. Input the length and width of a rectangle and calculate its perimeter using
the formula:
Perimeter = 2 × (length + width)
length = float(input("Enter length of rectangle: "))
width = float(input("Enter width of rectangle: "))

perimeter = 2 * (length + width)


print("Perimeter of rectangle:", perimeter)

Q6. Calculate compound interest using:


A = P * (1 + r/n) ^ (n*t)
where P = 2000, r = 0.05, n = 4, t = 3.
P = 2000
r = 0.05
n = 4
t = 3

A = P * (1 + r/n) ** (n*t)
print("Final Amount after Compound Interest: ₹", round(A, 2))

Q7. Write a program that takes weight (kg) and height (m) as input and
calculates BMI using:
BMI = weight / (height * height)
weight = float(input("Enter your weight (in kg): "))
height = float(input("Enter your height (in meters): "))

BMI = weight / (height * height)


print("Your BMI is:", round(BMI, 2))

Q8. Convert ₹10,000 into USD, assuming 1 USD = ₹83.5. Print the result rounded
to 2 decimal places.
inr = 10000
usd_rate = 83.5

usd = inr / usd_rate


print("Amount in USD: $", round(usd, 2))

Q9. Write a Python program to print all numbers from 50 to 100 that are
divisible by 5 and 7 using a for loop.
for num in range(50, 101):
if num % 5 == 0 and num % 7 == 0:
print(num)
Q10. Create a dictionary student_scores with names and marks of 4 students.
Add a new student to the dictionary. Display names of students who scored
more than 75.
student_scores = {
"Alice": 82,
"Bob": 67,
"Charlie": 91,
"David": 74
}

# Adding a new student


student_scores["Eva"] = 88

# Display names who scored more than 75


print("Students who scored more than 75:")
for name, score in student_scores.items():
if score > 75:
print(name)

Q11. Write a function calculate_area(length, width) that returns the area of a


rectangle. Call the function with user inputs and display the result.
def calculate_area(length, width):
return length * width

l = float(input("Enter length: "))


w = float(input("Enter width: "))

area = calculate_area(l, w)
print("Area of rectangle:", area)

Q12. Create a CSV file products.csv with 4 columns: Product, Price, Quantity,
Category. Write a program using Pandas to load the file and:
- Display the first 3 rows.
- Show the total number of rows and columns.
- Print the average price of all products.
import pandas as pd

# Load CSV
df = pd.read_csv('products.csv')

# Display first 3 rows


print(df.head(3))

# Show total rows and columns


print("Shape of DataFrame:", df.shape)
# Average price
print("Average Price:", df['Price'].mean())

Q13. Given marks of students: [55, 65, 75, 85, 45, 90, 62, 78, 88, 72]. Create a
histogram showing the distribution of scores using bins of 10.
import matplotlib.pyplot as plt

marks = [55, 65, 75, 85, 45, 90, 62, 78, 88, 72]

plt.hist(marks, bins=range(40, 101, 10), edgecolor='black')


plt.title('Distribution of Student Marks')
plt.xlabel('Marks')
plt.ylabel('Number of Students')
plt.grid(True)
plt.show()

Create a NumPy array of the Salary column and calculate: • Mean, median, and standard
deviation • Normalize the Performance_Score column using NumPy so values range
between 0 and 1. • Using NumPy, find the employee(s) with the highest and lowest
Experience_Years. Q. Using the statistics module, calculate: • Mode of the Experience_Years
• Variance of the Performance_Score Q. Create the following plots using Matplotlib: •
Histogram of employee ages • Boxplot of salaries across all departments • Line plot showing
Performance_Score against Employee_ID how to use saved data set in pythomn

1. Loading the dataset:

You will typically use pandas to load a dataset from a CSV or Excel file. If your dataset is
saved as a CSV file, you can use the following code to load it:

python
Copy code
import pandas as pd

# Load the dataset


df = pd.read_csv('your_dataset.csv') # Replace with the correct path to
your dataset

If you have your dataset in an Excel file:

python
Copy code
df = pd.read_excel('your_dataset.xlsx') # Replace with the correct path
to
df = pd.read_csv(r'C:\Users\Lenovo\Documents\Python PG33\Employee_Dataset (1).csv')

df = pd.read_csv('C:/Users/Lenovo/Documents/Python PG33/Employee_Dataset (1).csv')

First, import libraries and read the data:


python
Copy code
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statistics

# Read the dataset


df = pd.read_csv(r'C:\Users\Lenovo\Documents\Python PG33\
Employee_Dataset (1).csv')

Q1. NumPy operations:

(a) Create a NumPy array of the Salary column and calculate mean, median, and standard
deviation:
python
Copy code
salary_array = np.array(df['Salary'])

# Mean
mean_salary = np.mean(salary_array)

# Median
median_salary = np.median(salary_array)

# Standard Deviation
std_salary = np.std(salary_array)

print(f"Mean Salary: {mean_salary}")


print(f"Median Salary: {median_salary}")
print(f"Standard Deviation of Salary: {std_salary}")

(b) Normalize the Performance_Score column between 0 and 1:


python
Copy code
performance_array = np.array(df['Performance_Score'])

# Min-Max normalization
performance_normalized = (performance_array - np.min(performance_array))
/ (np.max(performance_array) - np.min(performance_array))

print(performance_normalized)

(c) Find the employee(s) with highest and lowest Experience_Years:


python
Copy code
experience_array = np.array(df['Experience_Years'])

# Highest Experience
max_experience = np.max(experience_array)
max_experience_employees = df[df['Experience_Years'] == max_experience]
# Lowest Experience
min_experience = np.min(experience_array)
min_experience_employees = df[df['Experience_Years'] == min_experience]

print("Employee(s) with highest experience:")


print(max_experience_employees)

print("\nEmployee(s) with lowest experience:")


print(min_experience_employees)

Q2. Using the statistics module:

(a) Mode of Experience_Years:


python
Copy code
mode_experience = statistics.mode(df['Experience_Years'])
print(f"Mode of Experience_Years: {mode_experience}")

(b) Variance of Performance_Score:


python
Copy code
variance_performance = statistics.variance(df['Performance_Score'])
print(f"Variance of Performance_Score: {variance_performance}")

Q3. Matplotlib Plots:

(a) Histogram of employee ages:


python
Copy code
plt.hist(df['Age'], bins=10, color='skyblue', edgecolor='black')
plt.title('Histogram of Employee Ages')
plt.xlabel('Age')
plt.ylabel('Number of Employees')
plt.grid(True)
plt.show()

(b) Boxplot of salaries across all departments:


python
Copy code
# Group salaries by Department
departments = df['Department'].unique()

# Create salary lists per department


salary_data = [df[df['Department'] == dept]['Salary'] for dept in
departments]

plt.boxplot(salary_data, labels=departments)
plt.title('Boxplot of Salaries across Departments')
plt.xlabel('Department')
plt.ylabel('Salary')
plt.xticks(rotation=45)
plt.grid(True)
plt.show()

(c) Line plot showing Performance_Score against Employee_ID:


python
Copy code
plt.plot(df['Employee_ID'], df['Performance_Score'], marker='o',
linestyle='-')
plt.title('Performance Score vs Employee ID')
plt.xlabel('Employee ID')
plt.ylabel('Performance Score')
plt.grid(True)
plt.show()

Would you also like me to pack all of this nicely into one clean .ipynb (Jupyter notebook)
file so you can directly upload and run? 🚀
(Just say "yes"!)

4o

You said:
how to save this file

ChatGPT said:

No problem! I'll guide you —


you have two ways to save this work, depending on what you're using:

1. If you're using Jupyter Notebook:

 Copy the code I gave you into a new Jupyter Notebook (.ipynb).
 Go to File → Save and Checkpoint
or simply press Ctrl + S.
 It saves automatically as a .ipynb file (a Notebook file).

If you want to download it, you can also go to:


File → Download as → Notebook (.ipynb) or even as a .py script!

2. If you want to save it as a Python Script (.py file):

 Open any text editor like VS Code, Notepad++, PyCharm, or even basic Notepad.
 Paste the entire code.
 Save the file with a .py extension, for example:

Copy code
employee_analysis.py

 While saving, select Save as type: All Files, not .txt, and make sure the filename
ends with .py.

✅ After saving:

 You can run .py files from the Command Prompt by:

bash
Copy code
python filename.py

You might also like