Q1. Scenario: Write a function that takes a list of numbers and returns the mean (average). Then use it to compute mean of [5,10,15,20].
def mean(nums): return sum(nums)/len(nums) if nums else 0. Call: result = mean([5,10,15,20]) returns 12.5. Functions encapsulate reusable logic. Handle empty list to avoid division by zero. This is a building block for data analysis.
Q2. Scenario: In a machine learning pipeline, you need a function to standardize data (subtract mean, divide by standard deviation). Write a function that takes a list and returns standardized list. Use help from statistics module.
import statistics; def standardize(data): mu = statistics.mean(data); sigma = statistics.stdev(data); return [(x - mu)/sigma for x in data]. Example: standardize([1,2,3]) yields [-1.224,0,1.224]. This is feature scaling.
Q3. Scenario: Write a function that computes mean squared error (MSE) between two lists of predictions and actuals. Use it with y_true = [3, -0.5, 2, 7] and y_pred = [2.5, 0.0, 2, 8].
def mse(y_true, y_pred): return sum((t-p)**2 for t,p in zip(y_true, y_pred))/len(y_true). For given values: ((0.5)^2 + (0.5)^2 + 0^2 + (-1)^2)/4 = (0.25+0.25+0+1)/4 = 1.5/4 = 0.375. MSE is a common regression loss.
Q4. Scenario: Write a function using *args to sum any number of arguments. Then write another using **kwargs to print key-value pairs. Demonstrate both.
def sum_all(*args): return sum(args). sum_all(1,2,3,4)=10. def print_kwargs(**kwargs): for k,v in kwargs.items(): print(f"{k}: {v}"). print_kwargs(name="Alice", age=30). *args collects positional, **kwargs collects keyword arguments.
Q5. Scenario: Create a function that returns a function to add a constant. For example, make_adder(5) returns a function that adds 5 to any number. Then use it to add 5 to 10.
def make_adder(x): def adder(y): return x+y; return adder. add5 = make_adder(5); add5(10) returns 15. This is a closure (function factory), useful for creating parameterized operations like feature transforms.
