Python Practice Marathon — 30 Coding Problems
Consolidate everything from Sessions 16–23. Thirty problems spanning Python basics, NumPy, Pandas, and visualization — try each before revealing the solution.
How to Use This Marathon
- Type it, don't read it. Run every snippet — muscle memory beats recognition.
- Predict before you run. Write down the expected output first.
- Narrate out loud. This is exactly what a live-coding round feels like.
Part A — Python Basics (Problems 1–5)
1. Print each number in [10, 20, 30, 40] using a for loop.
for n in [10, 20, 30, 40]:
print(n)2. Write a function that returns "High"/"Medium"/"Low" for a balance.
def categorize(balance):
if balance >= 100000:
return "High"
elif balance >= 30000:
return "Medium"
return "Low"3. Use a list comprehension to get the squares of 0–9.
squares = [x**2 for x in range(10)]4. Create a dictionary and print only the keys whose values exceed 50000.
balances = {"Aarav": 25000, "Priya": 120000, "Rahul": 8000}
for k, v in balances.items():
if v > 50000:
print(k)5. Remove duplicates from a list using a set.
cities = ["Mumbai", "Delhi", "Mumbai", "Chennai"]
unique = list(set(cities))Part B — NumPy (Problems 6–10)
6. Create a NumPy array [10, 20, 30, 40, 50] and compute its mean and max.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr.mean()) # 30.0
print(arr.max()) # 507. Multiply every element of that array by 2 (vectorized).
arr * 2 # [20 40 60 80 100]8. Reshape np.arange(6) into a 2×3 array.
np.arange(6).reshape(2, 3)9. Select the first three elements of the array via slicing.
arr[0:3] # [10 20 30]10. Add 100 to every element (broadcasting).
arr + 100 # [110 120 130 140 150]Part C — Pandas: Creating & Selecting (Problems 11–15)
11. Create a DataFrame with columns product, price, units.
import pandas as pd
df = pd.DataFrame({
"product": ["Pen", "Notebook", "Eraser"],
"price": [25, 120, 10],
"units": [10, 5, 20]
})12. Read a CSV file into a DataFrame.
df = pd.read_csv("sales.csv")13. Print the shape, columns, and first 5 rows.
print(df.shape)
print(df.columns)
print(df.head())14. Select the price column using both loc and iloc.
df.loc[:, "price"] # label-based
df.iloc[:, 1] # position-based15. Select the first row using both loc and iloc.
df.loc[0] # label
df.iloc[0] # positionPart D — Pandas: Filtering & Cleaning (Problems 16–20)
16. Count missing values per column.
df.isnull().sum()17. Drop rows with any missing value.
df.dropna()18. Fill missing values in the price column with the column mean.
df["price"] = df["price"].fillna(df["price"].mean())19. Remove duplicate rows.
df = df.drop_duplicates()20. Filter rows where balance is greater than 50000.
df[df["balance"] > 50000]Part E — Pandas: groupby & Merge (Problems 21–25)
21. Total sales per region using groupby.
df.groupby("region")["sales"].sum()22. Sum and mean sales per region using agg.
df.groupby("region")["sales"].agg(["sum", "mean"])23. Merge two DataFrames on a shared key column (left join).
pd.merge(orders, customers, on="customer_id", how="left")24. Concatenate two DataFrames vertically.
pd.concat([df1, df2])25. Create a pivot table of sales by region (rows) × product (columns).
df.pivot_table(index="region", columns="product",
values="sales", aggfunc="sum")Part F — Visualization & Mini-EDA (Problems 26–30)
26. Create a line plot of sales over time.
import matplotlib.pyplot as plt
plt.plot(months, sales)
plt.show()27. Create a bar chart of sales by region.
plt.bar(regions, sales_by_region)
plt.show()28. Create a histogram of the sales column.
plt.hist(df["sales"], bins=10)
plt.show()29. Create a Seaborn countplot of the region column.
import seaborn as sns
sns.countplot(x="region", data=df)
plt.show()30. Boxplot of sales by region, plus describe().
sns.boxplot(x="region", y="sales", data=df)
plt.show()
df.describe()Interview Questions — Python Live-Coding Classics
The Python questions interviewers ask again and again. Self-test before revealing.
IQ1. What are the core Python skills a data analyst needs?
Model answer: "Python basics (data structures, loops, functions), NumPy for arrays, Pandas for tabular data — selecting, cleaning, grouping — and Matplotlib/Seaborn for visualization."
IQ2. How do you approach a Python live-coding question?
Model answer: "I restate the task, outline my approach in words, write the code, then walk through the expected output. I'd rather narrate a clear plan than rush to code silently."
IQ3. Which library would you use to clean and aggregate tabular data?
Model answer: "Pandas — I'd use read_csv to load it, dropna/fillna for missing values, drop_duplicates for duplicates, and groupby to aggregate."
IQ4. How do you decide between a loop and a vectorized operation?
Model answer: "For numerical work on arrays, I use vectorized NumPy/Pandas operations — they're faster and cleaner. I use a loop only when the logic can't be expressed as a vectorized operation."
IQ5. What's the difference between dropna and fillna?
Model answer: "dropna removes rows/columns with missing values; fillna replaces them with a value. I choose based on how much data I'd lose and why it's missing."
IQ6. How do you group data and aggregate in Pandas?
Model answer: "With df.groupby('col')['metric'].sum() — or .agg(['sum','mean'])
for multiple stats. It's the Pandas equivalent of SQL GROUP BY."
IQ7. How do you visualize results after analysis?
Model answer: "With Matplotlib for basic plots — line, bar, histogram, scatter — and Seaborn for statistical plots like countplot, boxplot, and heatmap."
IQ8. Walk me through a simple end-to-end analysis in Python.
Model answer: "Load with read_csv → inspect with shape/head/info → clean missing/duplicates → summarize with describe and groupby → visualize distributions and relationships → write insights."
Key Takeaways
Type every snippet — Python is learned by running, not reading.
Vectorize with NumPy/Pandas instead of looping where possible.
loc = labels, iloc = positions; groupby = aggregate; merge = join.
Narrate your approach out loud in a live-coding round.
You've completed the full Python stack — ready for any Python round.
Objective Questions — Test Your Understanding
Q1. Which expression builds a list of squares of 0–9?
Q2. Which method removes rows with missing values in Pandas?
Q3. Which method groups data by a column and aggregates?
Q4. Which Matplotlib function creates a line plot?
Q5. Which Pandas function combines DataFrames on a shared key column?