Calculating Confidence Interval at a certain confidence level def get_ci(mean, cl, sd):
  loc = stats.norm.ppf(1 - cl/2)
  rng_val = stats.norm.cdf(loc - mean/sd)

  lwr_bnd = value - rng_val
  upr_bnd = value + rng_val 

  return_val = (lwr_bnd, upr_bnd)
  return(return_val)


This function takes three parameters which are the following:

mean --&gt; It is the mean
cl --&gt; Confidence Level
sd --&gt; Standard Deviation


Can someone explain how this function is working as for example if we are calculating 95% confidence interval, why can't we just return (-2*sd+mean,2*sd+mean)?
The CI is defined as the interval which contains your mean with a $\alpha$% of probability.

Given that you are using a model which its subjacent assumption is normality (amongst others), the interval is to be obtained comparing the probability in the context of a normal distribution.

The function stats.norm.cdf returns the probability of $loc - \frac{mean}{sd}$ being zero.

The value returned is the $(\bar{X} - Z_{\alpha}\sigma,\bar{X} + Z_{\alpha}\sigma)$.

We can't return $(-2 sd+mean,2 sd+mean)$ because it would not be general in terms of probability, we use tables which say $0.95 \rightarrow 2$ because we (humans) cannot calculate the number for every probability, but the stats.norm.cdf function can.

$Z_{\alpha}$ is difficult for us to have all the possible values (what if we need 90%, 95%, 99%, 99.9% or 70% probability?)