← 30 Days of Python
Day 28 / 30Best Practices

Virtual Environments & Python Best Practices

Professional Python work requires clean environments, readable code, and reproducible setups. Interviewers at product companies and MNCs will ask about these — they reveal whether you have worked in a real team.

1
Easy

What is a virtual environment and why do you use one?

Python Answer
# Create:
python -m venv myenv

# Activate:
source myenv/bin/activate       # Mac/Linux
myenv\Scripts\activate           # Windows

# Install packages:
pip install pandas numpy matplotlib

# Save dependencies:
pip freeze > requirements.txt

# Install from requirements:
pip install -r requirements.txt
💡

A virtual environment is an isolated Python installation with its own packages. Without it, all projects share packages — version conflicts arise when one project needs pandas 1.x and another needs 2.x. Always create a venv per project.

2
Easy

What is PEP 8 and what are the key style rules?

Python Answer
# Good PEP 8 style:
def calculate_growth_rate(current_value, previous_value):
    if previous_value == 0:
        return 0
    return (current_value - previous_value) / previous_value * 100

# Bad style (fails PEP 8):
def calcGrowthRate(c,p):
  if p==0: return 0
  return(c-p)/p*100
💡

PEP 8 is the Python style guide. Key rules: snake_case for functions/variables, 4-space indentation, spaces around operators, lines ≤79 chars, blank lines between functions. Use autopep8 or black to auto-format.

3
Medium

How do you write good docstrings?

Python Answer
def clean_dataframe(df, drop_cols=None, fill_value=0):
    """
    Clean a DataFrame by dropping specified columns and filling nulls.

    Parameters
    ----------
    df : pd.DataFrame
        Input DataFrame to clean.
    drop_cols : list, optional
        Columns to drop. Default None.
    fill_value : int or float
        Value to fill NaN. Default 0.

    Returns
    -------
    pd.DataFrame
        Cleaned DataFrame.
    """
    if drop_cols:
        df = df.drop(columns=drop_cols)
    return df.fillna(fill_value)
💡

Docstrings document the function for other developers (and your future self). The NumPy/Google style is used in data science projects. Tools like Sphinx auto-generate documentation from docstrings.

4
Medium

What is logging and why is it better than print() in production code?

Python Answer
import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s — %(levelname)s — %(message)s",
    filename="pipeline.log"
)

logging.info("Starting data pipeline")
logging.warning("Missing values found: 152 rows")
logging.error("File not found: sales.csv")

# vs print:
print("done")  # not saved, no timestamp, no severity level
💡

logging writes to files, includes timestamps and severity levels, and can be turned off without changing code. print() only shows in the console. Automated scripts must use logging — without it, errors on scheduled runs are invisible.

5
Medium

What are type hints and why do you use them?

Python Answer
import pandas as pd
from typing import Optional, List

def process_sales(
    df: pd.DataFrame,
    region: str,
    top_n: int = 10,
    exclude_cols: Optional[List[str]] = None
) -> pd.DataFrame:
    """
    Process sales DataFrame for a given region.
    """
    result = df[df["region"] == region]
    return result.head(top_n)
💡

Type hints tell other developers (and IDEs) what types a function expects and returns. They are not enforced at runtime but make code far more readable and enable IDE auto-complete and static analysis tools like mypy.

EVIKA ACADEMY · PYTHON FOR DATA ANALYTICS

Want to master Python with live practice?

Join our Python for Data Analysis course — live classes in Noida and online across India.

Book Free Demo Class →
← PREVIOUSDay 27: OOP Basics for Data AnalystsNEXT →Day 29: Python Coding Challenges for Analysts
Best Data Analytics Course in Noida Delhi NCR | EVIKA ACADEMY