Python Functions – Detailed Explanation
(Concept + Internal Working)
A function in Python is a structured, reusable block of code designed to perform a specific task.
Functions help break large programs into smaller, manageable, and logically organized parts.
1Why Functions Are Important
Functions improve:
✅ Code Reusability
Write once, use multiple times.
✅ Modularity
Break complex programs into smaller logical components.
✅ Maintainability
Easy to debug and update.
✅ Readability
Improves clarity and structure of code.
2Defining a Function
In Python, functions are created using the def keyword.
Syntax:
def function_name(parameters):
"""Docstring (optional)"""
statement(s)
return value
Example:
def greet():
print("Hello, Welcome to Python!")
Calling the Function:
greet()
Explanation:
def → Keyword to define function
greet → Function name
() → Parameter list (empty here)
Indentation → Defines function body
Function runs only when called
3Function Parameters and Arguments
Parameters
Variables defined in function declaration.
Arguments
Actual values passed when calling the function.
Example:
def add(a, b): # a and b are parameters
return a + b
result = add(10, 5) # 10 and 5 are arguments
print(result)
Internal Working:
1. add(10, 5) is called
2. a = 10, b = 5
3. Function computes a + b
4. Returns 15
5. Stored in result
4Types of Arguments (Very Important
Concept)
1. Positional Arguments
Order matters.
def student(name, age):
print(name, age)
student("Arul", 21)
If order changes → incorrect mapping.
2. Keyword Arguments
Order does NOT matter.
student(age=21, name="Arul")
3. Default Arguments
Default value assigned if argument not provided.
def greet(name="Guest"):
print("Hello", name)
greet() # Hello Guest
greet("Arul") # Hello Arul
4. Variable-Length Arguments
*args (Tuple format)
Used when number of inputs is unknown.
def total(*numbers):
print(type(numbers))
return sum(numbers)
print(total(10, 20, 30, 40))
Here:
numbers becomes a tuple → (10, 20, 30, 40)
**kwargs (Dictionary format)
Used for keyword variable arguments.
def details(**info):
print(info)
details(name="Arul", dept="Mechanical", age=30)
Here:
info becomes dictionary → {'name': 'Arul', 'dept': 'Mechanical', 'age': 30}
5Return Statement
The return keyword sends output back to the caller.
Important Points:
Function stops execution after return
Multiple values can be returned (as tuple)
Example:
def calculation(a, b):
sum_val = a + b
diff = a - b
return sum_val, diff
result = calculation(10, 5)
print(result)
Output:
(15, 5)
6Local vs Global Variables
Local Variable
Declared inside function → accessible only inside.
def test():
x = 10
print(x)
Global Variable
Declared outside function.
x = 100
def show():
print(x)
show()
Modifying Global Variable
x = 10
def change():
global x
x = 50
change()
print(x)
7Lambda Functions (Anonymous Functions)
Small one-line functions.
Syntax:
lambda arguments: expression
Example:
square = lambda x: x * x
print(square(5))
Used commonly with:
map()
filter()
sorted()
8Recursive Functions
A function calling itself.
Example: Factorial
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
How it works:
factorial(5)
= 5 × factorial(4)
= 5 × 4 × factorial(3)
= 5 × 4 × 3 × factorial(2)
= 5 × 4 × 3 × 2 × factorial(1)
= 120
9Function Scope (LEGB Rule – Advanced
Concept)
Python searches variables in this order:
L → Local
E → Enclosing
G → Global
B → Built-in
This is called the LEGB Rule.
[Link]-Order Functions
A function that:
Takes another function as argument OR
Returns another function
Example:
def greet(func):
func()
def say_hello():
print("Hello")
greet(say_hello)
11 Decorators (Advanced Concept)
A decorator modifies another function.
def decorator_function(original_function):
def wrapper():
print("Before execution")
original_function()
print("After execution")
return wrapper
@decorator_function
def display():
print("Hello")
display()
12Functions in Data Science
Applying functions to DataFrames:
import pandas as pd
def convert_upper(text):
return [Link]()
df['Name'] = df['Name'].apply(convert_upper)
Functions are heavily used in:
Data Cleaning
Feature Engineering
Transformation
EDA
Applying Functions to DataFrames (Using
Pandas)
In Data Science and data analysis, applying functions to DataFrames is a core operation used
for:
Data cleaning
Feature engineering
Data transformation
Creating new columns
Aggregation
Conditional modification
We typically use the pandas library for DataFrame operations.
1Creating a Sample DataFrame
import pandas as pd
data = {
'Name': ['Arul', 'John', 'Meena'],
'Marks': [85, 92, 78]
}
df = [Link](data)
print(df)
2 Using .apply() on a Single Column
.apply() applies a function to each element of a Series (column).
Example: Convert names to uppercase
def convert_upper(text):
return [Link]()
df['Name'] = df['Name'].apply(convert_upper)
Explanation:
df['Name'] → Selects column
.apply(convert_upper) → Applies function to each row value
Returns transformed column
3Using Lambda Function with .apply()
Instead of defining a separate function:
df['Marks'] = df['Marks'].apply(lambda x: x + 5)
Here:
Each value in Marks increases by 5.
4 Creating a New Column Using .apply()
Example: Grade Classification
def grade(marks):
if marks >= 90:
return "A"
elif marks >= 80:
return "B"
else:
return "C"
df['Grade'] = df['Marks'].apply(grade)
Now the DataFrame has a new column Grade.
5Applying Function Row-Wise (axis=1)
When you want to use multiple columns:
def result_status(row):
if row['Marks'] >= 80:
return "Pass"
else:
return "Fail"
df['Result'] = [Link](result_status, axis=1)
Why axis=1?
axis=0 → column-wise (default)
axis=1 → row-wise
6Using .map() (For Single Column Only)
.map() works like apply but only for Series.
df['Marks'] = df['Marks'].map(lambda x: x * 2)
OR dictionary mapping:
grade_map = {'A': 'Excellent', 'B': 'Good', 'C': 'Average'}
df['Grade_Desc'] = df['Grade'].map(grade_map)
7Using .applymap() (Entire DataFrame)
Applies function to every element.
df_numeric = [Link]([[1,2],[3,4]])
df_squared = df_numeric.applymap(lambda x: x**2)
8Using Built-in Functions
You can directly apply built-in functions:
df['Name'] = df['Name'].apply(len)
9Using .transform() (Important in GroupBy)
Used with grouped data:
df['Normalized'] = [Link]('Grade')['Marks'].transform(lambda x: x -
[Link]())
Used for:
Standardization
Normalization
Feature scaling
[Link] Consideration
⚠ .apply() is slower than vectorized operations.
Instead of:
df['Marks'] = df['Marks'].apply(lambda x: x + 10)
Better (vectorized):
df['Marks'] = df['Marks'] + 10
Vectorized operations are:
Faster
More memory efficient
Optimized internally
11Real Data Science Example
Cleaning Missing Values
df['Marks'] = df['Marks'].apply(lambda x: 0 if [Link](x) else x)
12 When to Use What?
Method Use Case
apply() Custom logic
map() Single column mapping
applymap() Entire DataFrame
transform() Group operations
Vectorized ops Fast numeric operations