Functions — Definition, Arguments & Scope
Writing reusable functions is what separates analysts who script from analysts who code. Every real Python project uses custom functions. Interviewers test this to see if you write production-quality code.
How do you define and call a function in Python?
def greet(name):
return f"Hello, {name}!"
result = greet("Priya") # "Hello, Priya!"Functions encapsulate logic so it can be reused. In data work, you write functions like clean_phone(number), standardise_city(name), or compute_kpi(df) that are applied across columns or DataFrames.
What are default arguments and keyword arguments?
def describe(name, role="Analyst", city="Noida"):
return f"{name} is a {role} in {city}"
describe("Rahul") # uses defaults
describe("Priya", city="Delhi") # keyword arg
describe("Aman", "Engineer", "Mumbai") # positionalDefault arguments make functions flexible. In Pandas functions like pd.read_csv(), almost everything is a keyword argument with a sensible default. Understanding this helps you read library docs.
What are *args and **kwargs?
def total(*args): # any number of positional args
return sum(args)
total(1, 2, 3, 4) # 10
def info(**kwargs): # any number of keyword args
for k, v in kwargs.items():
print(k, v)
info(name="Rahul", age=28)*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. Used in wrapper functions and when the number of parameters is unknown — common in analytics utility functions.
What is a lambda function?
# Regular function:
def square(x):
return x ** 2
# Lambda equivalent:
square = lambda x: x ** 2
square(5) # 25
# Common in Pandas:
df["salary_lakhs"] = df["salary"].apply(lambda x: round(x / 100000, 2))Lambda functions are anonymous one-liners. They are most useful inside .apply(), map(), sorted(), and filter(). For anything more than one line, use a regular def — readability matters.
What is variable scope — local vs global?
x = 10 # global
def modify():
x = 20 # local — does not affect global x
print(x) # 20
modify()
print(x) # 10 — unchanged
# To modify global:
def modify_global():
global x
x = 20Variables inside a function are local by default. Avoid global variables in data scripts — they make code hard to debug. Pass values as arguments and return results instead.
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 →