0% found this document useful (0 votes)
3 views20 pages

Python WordProblems

The document provides a series of Python programming exercises related to lists, strings, NumPy arrays, dictionaries, and Pandas DataFrames, aimed at MBA Business Analytics students. Each section includes scenarios, tasks, and sample code solutions for practical applications in business analytics. The exercises cover topics such as calculating averages, string manipulation, data analysis with NumPy and Pandas, and file I/O operations.

Uploaded by

Gokul Unni
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)
3 views20 pages

Python WordProblems

The document provides a series of Python programming exercises related to lists, strings, NumPy arrays, dictionaries, and Pandas DataFrames, aimed at MBA Business Analytics students. Each section includes scenarios, tasks, and sample code solutions for practical applications in business analytics. The exercises cover topics such as calculating averages, string manipulation, data analysis with NumPy and Pandas, and file I/O operations.

Uploaded by

Gokul Unni
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

BAE543A — Introduction to Python

Word Problems & Real-World Scenarios


MBA Business Analytics | Semester III | M.S. Ramaiah University

PART 1 — Notebook Practice Questions


Section A: Lists & Slicing
Q1 — Average of a List
Scenario:
You are a sales analyst at a retail company. Your manager gives you the monthly
revenue figures for three months: January = ₹1,05,000, February = ₹2,03,000, and
March = ₹3,10,000. He asks you to write a Python program to calculate the average
monthly revenue for the quarter.

Task: Store the values in a list and calculate the average using a for loop.

Answer:
Loop through the list to find the total, then divide by the number of months (3). Average
= (1,05,000 + 2,03,000 + 3,10,000) / 3 = ₹2,06,000

example = [105000, 203000, 310000]


total = 0
for i in example:
total += i
print('Average Revenue:', total / len(example))
# Output: Average Revenue: 206000.0

Q2 — Slice First 2 Elements


Scenario:
You are a data analyst at a bank. You have a list of the top 3 loan applicants ranked by
credit score: [750, 690, 610]. Your manager wants to see only the top 2 applicants who
qualify for the premium loan scheme. Write Python code to extract only the first 2 scores
from the list.

Task: Use list slicing to get the first 2 elements.

Answer:
Use lst[:2] — starts from index 0 and stops before index 2. Returns the first 2 elements.

scores = [750, 690, 610]


print(scores[:2])
# Output: [750, 690]

Q3 — Slice Last 2 Elements


Scenario:
You are a supply chain manager tracking delivery times (in days) for 3 vendors: [4, 7,
12]. The last 2 vendors have been flagged for review due to delays. Write Python code
to extract only the last 2 delivery times for the review report.

Task: Use negative indexing to slice the last 2 elements.

Answer:
Use lst[-2:] — negative index counts from the end. -2 starts 2 positions from the end and
goes till the last element.

delivery_times = [4, 7, 12]


print(delivery_times[-2:])
# Output: [7, 12]

Q4 — Slice From Index 1 Onwards


Scenario:
You work at an e-commerce company. You have a ranked list of top 3 products by
sales: ['#1 iPhone', '#2 MacBook', '#3 AirPods']. The top product is already featured on
the homepage. You need to extract the remaining products for a secondary promotion
banner. Write code to skip the first product and get the rest.

Task: Use slicing to get all elements from index 1 onwards.

Answer:
Use lst[1:] — starts at index 1 and goes all the way to the end. Skips the first element.

products = ['iPhone', 'MacBook', 'AirPods']


print(products[1:])
# Output: ['MacBook', 'AirPods']

Section B: Strings
Q5 — Reverse a String Using a Loop
Scenario:
You are a junior developer at a cybersecurity firm. Your team is building a basic
encryption tool that reverses input strings as a first step before encoding. Write a Python
function that takes a password string as input and returns it reversed — using a for loop
(not slicing), so the team can understand each step of the reversal.

Task: Write a function to reverse a string character by character using a loop.

Answer:
Loop through each character and prepend it to a result string: result = character + result.
This builds the reversed string one character at a time from front.

def reverse_str(mystr):
result = ''
for i in mystr:
result = i + result
print(result)

reverse_str('SecurePass')
# Output: ssaPeruceS

Q6 — Reverse a String Using Slicing


Scenario:
Same cybersecurity tool as above, but your senior developer says — why write a loop
when Python can do it in one line? Rewrite the reversal function using Python slicing so
it is cleaner and more efficient for production use.

Task: Reverse the same string using [::-1] slicing in a single line.

Answer:
Use s[::-1] — slice with step -1 walks the string backwards from end to start. Produces
the same result as the loop method but in one line.

def reverse_str(s):
print(s[::-1])

reverse_str('SecurePass')
# Output: ssaPeruceS

Section C: NumPy Arrays


Q7 — NumPy Array Mean
Scenario:
You are a portfolio analyst at a mutual fund. Your fund holds 5 stocks with the following
annual returns (%): TCS = 10, Infosys = 9, Wipro = 7.5, HCL = 6, Reliance = 14. Your
client wants to know the average return of the portfolio. Write a Python function using
NumPy to calculate this.

Task: Create a NumPy array of the returns and find the mean.

Answer:
Use [Link]() to store returns, then call .mean() to calculate average.
(10+9+7.5+6+14)/5 = 9.3%

import numpy as np
returns = [Link]([10, 9, 7.5, 6, 14])
print('Average Portfolio Return:', [Link](), '%')
# Output: Average Portfolio Return: 9.3 %

Q8 — Standard Deviation of NumPy Array


Scenario:
Same portfolio from Q7. Your risk management team needs to assess how volatile the
portfolio is. A higher standard deviation means the returns vary a lot (risky). A lower one
means the returns are consistent (stable). Write Python code to calculate the standard
deviation of the portfolio returns.

Task: Calculate standard deviation of the same NumPy array using .std()

Answer:
Use [Link]() — NumPy calculates population std deviation (divides by N). Result =
2.713, meaning returns vary by about 2.71% from the mean on average.

import numpy as np
returns = [Link]([10, 9, 7.5, 6, 14])
print('Portfolio Risk (Std Dev):', [Link]())
# Output: Portfolio Risk (Std Dev): 2.713

Section D: Dictionaries
Q9 — Iterate Over Dictionary
Scenario:
You are an analyst at a stock brokerage. You have a dictionary storing 3 stocks and
their year-end returns: {'A': 15, 'B': 10, 'C': 11}. Your manager wants a printed report
showing each stock and its return. Write a Python program to loop through the dictionary
and print each stock with its return value.
Task: Iterate over the dictionary and print each key-value pair.

Answer:
Looping over a dictionary gives you keys by default. Use d[key] to fetch the value for
each key.

stock_returns = {'A': 15, 'B': 10, 'C': 11}


for stock in stock_returns:
print(stock, stock_returns[stock])
# Output:
# A 15
# B 10
# C 11

Q10 — Dictionary Keys and Length


Scenario:
You are a product manager at a startup. Your product catalogue is stored as a dictionary
where keys are product names and values are prices. Before sending the catalogue to
the marketing team, you need to: (1) List all product names, and (2) Tell them how many
products are in the catalogue. Write Python code to do both.

Task: Use .keys() to list all keys and len() to count entries.

Answer:
[Link]() returns all keys (product names). len(d) counts the total number of key-value
pairs (products).

catalogue = {'Laptop': 75000, 'Phone': 45000, 'Tablet': 30000}


print('Products:', [Link]())
print('Total Products:', len(catalogue))
# Output:
# Products: dict_keys(['Laptop', 'Phone', 'Tablet'])
# Total Products: 3

Q11 — Sum All Dictionary Values


Scenario:
You are a regional sales manager. Each key in your dictionary represents a sales region
and each value represents that region's monthly revenue (in lakhs): {'North': 15, 'South':
10, 'West': 11}. Calculate the total revenue across all regions using a for loop.
Task: Loop through the dictionary and sum all values.

Answer:
Start total = 0, loop through keys, access each value with d[key], and add to total. 15 +
10 + 11 = 36 lakhs total revenue.

revenue = {'North': 15, 'South': 10, 'West': 11}


total = 0
for region in revenue:
total += revenue[region]
print('Total Revenue:', total, 'Lakhs')
# Output: Total Revenue: 36 Lakhs

Section E: Pandas DataFrames


Q12 — Create a DataFrame from a Dictionary
Scenario:
You are a data analyst at a brokerage firm. You have performance data for 5 stocks: A
returned 10%, B returned 9%, C returned 7.5%, D returned 6%, and E returned 14%.
Create a structured DataFrame in Python from this data so it can be used for further
analysis and reporting.

Task: Create a Pandas DataFrame using a dictionary with stock names and returns.

Answer:
Pass a dictionary to [Link](). Keys become column names, list values become
rows. The result is a table just like an Excel sheet.

import pandas as pd
data = {
'Stock name': ['A', 'B', 'C', 'D', 'E'],
'Stock Returns': [10, 9, 7.5, 6, 14]
}
df = [Link](data)
print(df)

Q13 — Summary Statistics with .describe()


Scenario:
You just received a dataset of stock returns from your manager and need to present a
quick statistical summary to the investment committee — mean return, risk (std
deviation), minimum and maximum return, and quartiles. Instead of calculating each
manually, use Pandas to generate all statistics at once. Transpose the output for easier
reading.

Task: Run [Link]().transpose() on the stock returns DataFrame.

Answer:
[Link]() generates 8 statistics automatically — count, mean, std, min, 25%, 50%,
75%, max. .transpose() flips the table so it reads horizontally, which is easier when you
have multiple columns.

print([Link]().transpose())
# Output shows: count=5, mean=9.3, std=3.03, min=6.0, max=14.0

Q14 — Standard Deviation of a Column


Scenario:
Your risk team specifically wants to know the volatility (standard deviation) of just the
Stock Returns column — not the entire DataFrame. Write Python code to extract only
that column's standard deviation for the risk report.

Task: Calculate std deviation of the 'Stock Returns' column using df['column'].std()

Answer:
df['Stock Returns'].std() selects the column as a Series and calculates sample std
deviation (divides by N-1). Result = 3.033 — slightly higher than NumPy's .std() which
uses N instead of N-1.

print('Volatility:', df['Stock Returns'].std())


# Output: Volatility: 3.033

Q15 — Select a Single Column


Scenario:
You are preparing a presentation and need only the list of stock names from your
DataFrame — not the returns, not any other column. Write Python code to extract just
the 'Stock name' column from the DataFrame.

Task: Use df['column_name'] to select a single column.

Answer:
df['Stock name'] picks out that one column and returns it as a Pandas Series — a single
column with index numbers on the left. Like highlighting one column in Excel.
print(df['Stock name'])
# Output:
# 0 A
# 1 B
# 2 C
# 3 D
# 4 E

PART 2 — Previous Year Question Paper (SEE 2)


Question 1 — Functions, Loops & File I/O
Q1a — Check Odd or Even
Scenario:
You are a developer at a logistics company. The company assigns delivery routes by
odd/even split — odd-numbered order IDs go to Driver A, even-numbered to Driver B.
Write a Python function that takes an order ID as input and prints which driver should
handle it.

Task: Write a function using the modulus operator to check if a number is odd or
even.

Answer:
n % 2 gives the remainder when divided by 2. If remainder = 0, the number is even. If
remainder = 1, it is odd. Order 7 → Odd → Driver A. Order 4 → Even → Driver B.

def check_odd_even(n):
if n % 2 == 0:
print(n, 'is Even - Assign to Driver B')
else:
print(n, 'is Odd - Assign to Driver A')

check_odd_even(7) # Odd - Driver A


check_odd_even(4) # Even - Driver B

Q1b — Sum 1 to 50 Using While Loop


Scenario:
You are a finance intern at a company. Your manager asks you to calculate the total of
all employee serial numbers from 1 to 50, to verify a payroll batch total. Write a Python
function using a while loop to calculate this sum.

Task: Use a while loop to calculate sum of all integers from 1 to 50.
Answer:
Initialise total = 0 and counter i = 1. Keep adding i to total and increment i until i exceeds
50. Final answer = 1275.

def sum_1_to_50():
total = 0
i = 1
while i <= 50:
total += i
i += 1
print('Payroll Batch Total:', total)

sum_1_to_50() # Output: Payroll Batch Total: 1275

Q1c — Print Even Numbers Using For Loop


Scenario:
You work at a retail chain with 50 store locations numbered 1 to 50. The company has
decided to run a promotional event only at even-numbered stores this weekend. Write a
Python function to print all even store numbers so the operations team knows which
stores to activate.

Task: Use a for loop to print all even numbers between 1 and 50.

Answer:
Use range(2, 51, 2) — start at 2, stop before 51, step by 2. This directly generates only
even numbers without needing an if condition.

def print_even_stores():
print('Stores for promotion:')
for i in range(2, 51, 2):
print(i, end=' ')

print_even_stores()
# Output: 2 4 6 8 10 ... 50

Q1d — Write to a Text File


Scenario:
You are building an automated report system. At the end of each day, the system needs
to write a confirmation message to a log file called 'daily_log.txt'. The message should
say 'Hello Python' to confirm the script ran successfully. Write a Python function to do
this.
Task: Write a function that opens a file in write mode and saves a message.

Answer:
Use open('filename', 'w') to open the file in write mode. 'w' creates the file if it doesn't
exist and overwrites it if it does. Use 'with' so the file closes automatically after writing.

def write_to_file():
with open('daily_log.txt', 'w') as f:
[Link]('Hello Python')
print('Log file written successfully')

write_to_file()

Question 2 — Strings & Lists


Q2a — Remove Spaces from a String
Scenario:
You are a data engineer cleaning customer data. The customer name field often has
accidental spaces — for example 'Gokul N' gets entered as 'Go kul N'. Before storing
names in the database, you need to strip all spaces. Write a Python function to clean the
input string.

Task: Write a function to remove all spaces from a string using .replace()

Answer:
Use [Link](' ', '') — finds every space character and replaces it with nothing (empty
string). Spaces simply vanish.

def remove_spaces(s):
return [Link](' ', '')

print(remove_spaces('Go kul N'))


# Output: GokulN

Q2b — Convert String to Uppercase


Scenario:
Your company's CRM system stores city names entered by different users — some type
'mumbai', others type 'Mumbai', others 'MUMBAI'. Before comparing or grouping
records, you need to standardise all city names to uppercase. Write a Python function to
convert any city name to uppercase.
Task: Use .upper() to convert a string to all capitals.

Answer:
[Link]() is a built-in string method that converts every letter to uppercase. Numbers
and symbols are unaffected. This ensures 'mumbai', 'Mumbai', and 'MUMBAI' all
become 'MUMBAI' — identical for comparison.

def standardise_city(s):
return [Link]()

print(standardise_city('mumbai')) # MUMBAI
print(standardise_city('Mumbai')) # MUMBAI
print(standardise_city('MUMBAI')) # MUMBAI

Q2c — Add an Element to a List


Scenario:
You are managing a waitlist for a sold-out product launch. As customers register
interest, their names need to be added to the waitlist one by one. The current waitlist is
['Rahul', 'Priya', 'Ankit']. A new customer 'Sneha' just registered. Write a Python function
to add her to the list.

Task: Write a function that appends a new element to an existing list.

Answer:
[Link](element) adds the new item to the end of the list. The list grows by 1. It
modifies the original list directly — no new list is created.

def add_to_waitlist(lst, name):


[Link](name)
return lst

waitlist = ['Rahul', 'Priya', 'Ankit']


print(add_to_waitlist(waitlist, 'Sneha'))
# Output: ['Rahul', 'Priya', 'Ankit', 'Sneha']

Q2d — Max and Min of a List


Scenario:
You are a sales analyst reviewing quarterly performance across 5 regional teams. Their
sales figures (in lakhs) are: [32, 18, 45, 27, 39]. Your MD wants to know which region
performed best and which performed worst this quarter. Write a Python function to find
both.
Task: Use max() and min() to find the highest and lowest values in a list.

Answer:
max(lst) scans the entire list and returns the largest value. min(lst) returns the smallest.
Both are built-in Python functions — no loop needed.

def best_worst(sales):
print('Best Region Sales:', max(sales), 'Lakhs')
print('Worst Region Sales:', min(sales), 'Lakhs')

sales = [32, 18, 45, 27, 39]


best_worst(sales)
# Output:
# Best Region Sales: 45 Lakhs
# Worst Region Sales: 18 Lakhs

Question 3 — Dictionaries & Sets


Q3a — Dictionary of Cities and Temperatures
Scenario:
You are a data analyst at a weather forecasting startup. Your app needs to display
current average temperatures for 5 major Indian cities. Store the data in a Python
dictionary and write a function to print each city with its temperature in a readable
format.

Task: Create a dictionary with 5 city-temperature pairs and print them using .items()

Answer:
Dictionary stores key-value pairs. .items() returns both key and value together in each
loop iteration. f-string formats the output cleanly.

def city_temperatures():
temps = {
'Mumbai': 32, 'Delhi': 38,
'Bangalore': 28, 'Chennai': 35, 'Kolkata': 33
}
for city, temp in [Link]():
print(f'{city}: {temp}°C')

city_temperatures()

Q3b — Update a Dictionary Value


Scenario:
You manage a product pricing dictionary for an e-commerce platform: {'Laptop': 75000,
'Phone': 45000}. Due to a flash sale, the price of 'Phone' has been reduced to ₹39,999.
Write a Python function to update the price in the dictionary and return the updated
catalogue.

Task: Write a function that updates a value in a dictionary using direct key
assignment.

Answer:
d[key] = new_value — if the key exists, it updates the value. If the key doesn't exist, it
creates a new entry. Simple direct assignment, no special method needed.

def update_price(catalogue, product, new_price):


catalogue[product] = new_price
return catalogue

catalogue = {'Laptop': 75000, 'Phone': 45000}


print(update_price(catalogue, 'Phone', 39999))
# Output: {'Laptop': 75000, 'Phone': 39999}

Q3c — Intersection of Two Sets


Scenario:
Your company has two retail branches in Bengaluru. Branch A customers: {101, 102,
103, 104}. Branch B customers: {103, 104, 105, 106}. The marketing team wants to
identify customers who visited BOTH branches, so they can be targeted with a loyalty
reward campaign. Write Python code to find these common customers.

Task: Use the & operator or .intersection() to find common elements in two sets.

Answer:
s1 & s2 returns elements that exist in both sets. Customers 103 and 104 visited both
branches — they are the intersection.

def common_customers(branch_a, branch_b):


result = branch_a & branch_b
print('Loyalty reward targets:', result)

branch_a = {101, 102, 103, 104}


branch_b = {103, 104, 105, 106}
common_customers(branch_a, branch_b)
# Output: Loyalty reward targets: {103, 104}
Q3d — Difference Between Two Sets
Scenario:
Same two branches as Q3c. Now the marketing team wants to find customers who
visited Branch A but NOT Branch B — these are customers who haven't explored the
second branch yet. The team wants to send them an invitation to visit Branch B. Write
Python code to find these customers.

Task: Use the - operator to find elements in set A that are not in set B.

Answer:
s1 - s2 returns elements in s1 that do NOT exist in s2. Customers 101 and 102 visited
Branch A but not Branch B — these are the ones to target.

def branch_a_only(branch_a, branch_b):


result = branch_a - branch_b
print('Invite to Branch B:', result)

branch_a = {101, 102, 103, 104}


branch_b = {103, 104, 105, 106}
branch_a_only(branch_a, branch_b)
# Output: Invite to Branch B: {101, 102}

Question 4 — NumPy
Q4a — 3x3 Identity Matrix
Scenario:
You are a data scientist building a linear regression model from scratch. During matrix
operations, you need a 3x3 identity matrix to initialise the weight transformation step.
Write a Python function using NumPy to generate this matrix.

Task: Use [Link](3) to create a 3x3 identity matrix.

Answer:
[Link](3) creates a 3x3 matrix with 1s on the diagonal and 0s everywhere else.
Multiplying any matrix by the identity matrix gives back the same matrix — like
multiplying a number by 1.

import numpy as np

def identity_matrix():
matrix = [Link](3)
print(matrix)

identity_matrix()
# Output:
# [[1. 0. 0.]
# [0. 1. 0.]
# [0. 0. 1.]]

Q4b — Random Portfolio Weights


Scenario:
You are a portfolio manager at a hedge fund. You want to simulate a random allocation
of investment across 10 stocks. Generate 10 random weights that represent what
percentage of the total fund is invested in each stock. The weights must add up to
exactly 1 (i.e., 100% of the fund is allocated). Write a Python function to do this.

Task: Generate 10 random numbers and normalise them so they sum to 1.

Answer:
[Link](10) generates 10 random floats between 0 and 1. Dividing each by
the total sum (normalising) ensures they all add up to exactly 1 — standard practice in
portfolio theory.

import numpy as np

def portfolio_weights():
weights = [Link](10)
weights = weights / [Link]()
print('Weights:', weights)
print('Sum:', [Link]()) # Always 1.0

portfolio_weights()

Q4c — Reshape 2D Array to 1D


Scenario:
You are a machine learning engineer. Your image data is stored as a 2D NumPy array
(2 rows x 3 columns representing pixel blocks). Before feeding this data into your ML
model, it needs to be flattened into a single 1D array. Write a Python function to reshape
the 2D array into 1D.

Task: Use .flatten() or .reshape(-1) to convert a 2D array into 1D.

Answer:
[Link]() unrolls a multi-dimensional array into one single row. A 2x3 matrix has 6
elements total — flatten() converts it to [1 2 3 4 5 6]. ML models typically require 1D
input vectors.

import numpy as np

def flatten_image_data(arr):
flat = [Link]()
print('1D array:', flat)

image = [Link]([[1, 2, 3], [4, 5, 6]])


flatten_image_data(image)
# Output: 1D array: [1 2 3 4 5 6]

Q4d — Max and Min of NumPy Array


Scenario:
You are a risk analyst. Your fund has 5 stocks with portfolio weights [0.10, 0.25, 0.15,
0.30, 0.20]. The compliance team wants to know which stock has the highest allocation
(potential concentration risk) and which has the lowest (possibly underweighted). Write
Python code to find both.

Task: Use [Link]() and [Link]() to find highest and lowest values in a NumPy array.

Answer:
[Link]() scans the array and returns the largest value. [Link]() returns the smallest.
Can also be written as [Link](arr) and [Link](arr) — same result.

import numpy as np

def check_concentration(weights):
print('Highest allocation:', [Link]())
print('Lowest allocation:', [Link]())

weights = [Link]([0.10, 0.25, 0.15, 0.30, 0.20])


check_concentration(weights)
# Output:
# Highest allocation: 0.3
# Lowest allocation: 0.1

Question 5 — Pandas DataFrames


Q5a — Get Column Names
Scenario:
You just received a large dataset from a client. Before doing any analysis, you need to
quickly check what columns exist in the dataset. Write a Python function that loads a
DataFrame and prints all its column names — so you know what data you are working
with.

Task: Use [Link] or list([Link]) to get all column names.

Answer:
[Link] returns an Index object of all column names. list([Link]) converts it to a
plain Python list. Like reading the header row of an Excel sheet to understand the
dataset.

import pandas as pd

def get_columns(df):
print('Columns:', list([Link]))

df = [Link]({'Price': [100, 200], 'Cost': [60, 120], 'Region':


['North', 'South']})
get_columns(df)
# Output: Columns: ['Price', 'Cost', 'Region']

Q5b — Fill NaN Values with Zero


Scenario:
You are cleaning a sales dataset for a retail company. Some stores did not report their
sales figures for certain months, leaving blank (NaN) values in the DataFrame. For
calculation purposes, your team has decided that missing values should be treated as
zero sales. Write Python code to replace all NaN values with 0.

Task: Use [Link](0) to replace all missing values in a DataFrame.

Answer:
NaN = Not a Number, which represents a missing/blank value. [Link](0) replaces every
NaN in the entire DataFrame with 0. Without fixing NaN values, calculations like sum
and mean will either break or return NaN.

import pandas as pd, numpy as np

def fill_missing_sales(df):
df = [Link](0)
return df
df = [Link]({'Jan': [100, [Link], 300], 'Feb': [[Link], 200,
[Link]]})
print(fill_missing_sales(df))

Q5c — Load CSV into DataFrame


Scenario:
Your company stores its monthly sales data in a file called '[Link]'. Every Monday
morning, you need to load this file into Python to run your weekly analysis. Write a
Python function that loads the CSV, shows the first 5 rows to verify it loaded correctly,
and also prints the shape (how many rows and columns).

Task: Use pd.read_csv() to load a file, then use .head() and .shape to inspect it.

Answer:
pd.read_csv('[Link]') reads the file and creates a DataFrame. .head() shows the first 5
rows as a quick sanity check. .shape returns (number of rows, number of columns) —
confirms the data loaded completely.

import pandas as pd

def load_sales_data():
df = pd.read_csv('[Link]')
print('First 5 rows:')
print([Link]())
print('Shape:', [Link])
return df

df = load_sales_data()

Q5d — Create a New Profit Column


Scenario:
You are a financial analyst at a manufacturing company. Your DataFrame has two
columns — 'Price' (selling price) and 'Cost' (production cost) for 3 products. The CFO
wants a Profit column added to the dataset so she can see the margin on each product
directly. Write Python code to calculate and add the Profit column.

Task: Create a new column 'Profit' = Price - Cost using column arithmetic.

Answer:
df['Profit'] = df['Price'] - df['Cost'] subtracts Cost from Price for every row automatically —
no loop needed. It is exactly like adding a formula column =B2-C2 in Excel and dragging
it down.

import pandas as pd

df = [Link]({
'Product': ['A', 'B', 'C'],
'Price': [200, 350, 150],
'Cost': [120, 200, 80]
})
df['Profit'] = df['Price'] - df['Cost']
print(df)
# Output:
# Product Price Cost Profit
# A 200 120 80
# B 350 200 150
# C 150 80 70

Question 6 — Debugging
Q6 — Find and Fix 4 Errors in the Code
Scenario:
A junior developer at your firm wrote a Python script to calculate the average of a list of
numbers. The script is throwing errors and producing wrong results. Your manager has
asked you to review the code, identify all 4 bugs, explain what each error means, and
submit the corrected version.

Task: Identify 4 errors in the buggy code below and write the corrected version.

Buggy Code:
def calculate_average(list_of_numbers):
total = 0
for i in range(len(list_of_numbers) + 1): # Bug 1
total += list_of_numbers[i]
average = total / len(list_of_numbers) # Bug 4
return average

def main():
list_of_numbers = [10, 20, 30, 40]
avg = calculate_average(list_of_numbers)
print('Average is:', avg)
x = 10
result = x / y # Bug 2
print('Result is:', result)
print('Program complete' # Bug 3
main()
Answer:
Error 1: range(len(...) + 1) causes IndexError. List has 4 items (index 0-3). +1 tries to
access index 4 which doesn't exist. Fix: remove the +1. Error 2: Variable y is never
defined. result = x / y throws NameError. Fix: add y = 5 before that line. Error 3: Missing
closing parenthesis on print('Program complete'. Throws SyntaxError. Fix: add the
closing ). Error 4: average and return are indented inside the for loop — so it returns
after just the first iteration. Fix: dedent both lines out of the loop.

Corrected Code:
def calculate_average(list_of_numbers):
total = 0
for i in range(len(list_of_numbers)): # Fix 1
total += list_of_numbers[i]
average = total / len(list_of_numbers) # Fix 4: outside loop
return average

def main():
list_of_numbers = [10, 20, 30, 40]
avg = calculate_average(list_of_numbers)
print('Average is:', avg) # Output: 25.0
x = 10
y = 5 # Fix 2
result = x / y
print('Result is:', result)
print('Program complete') # Fix 3

main()

Good luck on your exam! You've got this.

You might also like