SAMANTUS Python for Data Analytics — Complete Training Manual MODULE 07
← Back to Course Index

Functions


On This Page

Module 7: Functions


7.1  Function Basics

A function is a reusable block of code that performs a specific task. Instead of writing the same code again and again, you define it once and simply 'call' it whenever needed.

► Defining and Calling a Function
def greet_student():
    print("Welcome to Samantus Web Training Institute!")

greet_student()   # calling the function
greet_student()   # can be called as many times as needed
Output
Welcome to Samantus Web Training Institute!
Welcome to Samantus Web Training Institute!
✓ Why Use Functions?
Functions make code reusable, organized, and easier to debug. Instead of copy-pasting the same 10 lines in five places, you write it once and call it five times.

7.2  Parameters & Arguments

Parameters are placeholders defined in the function itself; arguments are the actual values you pass in when calling the function.

► Function with Parameters
def greet(name):          # "name" is the parameter
    print(f"Hello, {name}! Welcome to Samantus.")

greet("Priya")            # "Priya" is the argument
greet("Rahul")
Output
Hello, Priya! Welcome to Samantus.
Hello, Rahul! Welcome to Samantus.

7.3  The return Statement

The return statement sends a value back from the function to wherever it was called — unlike print(), which only displays and does not give back a usable value.

► Function that Returns a Value
def calculate_gst(price):
    gst = price * 0.18
    return price + gst

final_price = calculate_gst(1000)
print("Final Price:", final_price)
Output
Final Price: 1180.0
✗ Common Mistake
Beginners often print() inside a function instead of using return, then wonder why they can't use the result later. Use return whenever you need the value for further calculations.

7.4  Default Parameters

You can give a parameter a default value, which is used automatically if the caller doesn't provide one.

► Default Parameter Example
def enroll_student(name, course="Digital Marketing"):
    print(f"{name} enrolled in {course}")

enroll_student("Anita")                 # uses default course
enroll_student("Vikram", "SEO")         # overrides default
Output
Anita enrolled in Digital Marketing
Vikram enrolled in SEO

7.5  Keyword Arguments

Keyword arguments let you pass values by explicitly naming the parameter, so order doesn't matter.

► Keyword Arguments Example
def student_info(name, age, course):
    print(f"{name}, Age {age}, Course: {course}")

# Using keyword arguments - order does not matter here
student_info(age=24, course="Google Ads", name="Meena")
Output
Meena, Age 24, Course: Google Ads

7.6  Lambda Functions

A lambda function is a small, anonymous, one-line function — useful for short operations where defining a full function feels unnecessary.

► Lambda Function Examples
square = lambda x: x * x
print(square(5))

add = lambda a, b: a + b
print(add(10, 20))

# Common use: sorting a list of tuples by the second value
students = [("Raj", 85), ("Meena", 92), ("Amit", 78)]
students.sort(key=lambda s: s[1], reverse=True)
print(students)
Output
25
30
[('Meena', 92), ('Raj', 85), ('Amit', 78)]
✓ Instructor Tip
Introduce lambda only after students are comfortable with normal functions — it's a shorthand, not a replacement, and can confuse beginners if taught too early.

7.7  Recursion

Recursion is when a function calls itself to solve a smaller version of the same problem, until it reaches a stopping point called the base case.

► Recursive Factorial Function
def factorial(n):
    if n == 0 or n == 1:      # base case - stops the recursion
        return 1
    return n * factorial(n - 1)   # recursive call

print(factorial(5))   # 5*4*3*2*1
Output
120
⚠ Important
Every recursive function MUST have a base case, or it will call itself forever and crash with a 'RecursionError: maximum recursion depth exceeded'.

7.8  Scope (Local vs Global)

Scope determines where a variable can be accessed. A local variable exists only inside the function where it's created; a global variable exists throughout the program.

► Local vs Global Scope
institute_name = "Samantus"   # global variable

def show_info():
    course = "SEO"            # local variable
    print(institute_name, "-", course)   # can read global here

show_info()
# print(course)   # This would cause an ERROR - course is local only
Output
Samantus - SEO

7.9  Mini Project — Fee Calculator Toolkit

Build a small toolkit of functions that could be used in a real training institute's billing system.

► fee_toolkit.py
def calculate_gst(amount, rate=0.18):
    return round(amount * rate, 2)

def apply_discount(amount, discount_percent=0):
    return round(amount - (amount * discount_percent / 100), 2)

def final_fee(base_fee, discount_percent=0):
    discounted = apply_discount(base_fee, discount_percent)
    gst = calculate_gst(discounted)
    return discounted + gst

print("Final Fee:", final_fee(15000, discount_percent=10))
Output
Final Fee: 15930.0

7.10  Practical Exercises

Basic (5 Questions)

1. Write a function that prints your name and course.

2. Write a function that takes a number and returns its square.

3. Write a function with a default parameter for 'city' set to 'Delhi'.

4. Write a function to add two numbers and return the result.

5. Write a lambda function to double a number.

Intermediate (5 Questions)

1. Write a function to check if a number is prime and return True/False.

2. Write a function using keyword arguments to build a student profile.

3. Write a recursive function to calculate the sum of numbers from 1 to n.

4. Write a function that returns the maximum of 3 numbers without using max().

5. Demonstrate local vs global scope with your own example (not from the notes).

Advanced (5 Questions)

1. Write a recursive function to calculate the Fibonacci number at position n.

2. Build a function-based 'Simple Interest Calculator' with principal, rate, and time as parameters (rate has a default value).

3. Use lambda with sorted() to sort a list of dictionaries by a specific key.

4. Write a function that takes any number of arguments using *args and returns their sum.

5. Build a small toolkit of 3 functions for a 'Marks Analyzer' (average, highest, grade) and combine them in one function.

7.11  Module Quiz (MCQs)

Q1. What keyword is used to define a function in Python?

Q2. What does the return statement do?

Q3. What is a lambda function?

Q4. What must every recursive function have?

Q5. A variable created inside a function is:

ℹ Answer Key
1-b, 2-b, 3-b, 4-b, 5-b

7.12  Module Assignment

Assignment: Build a Student Fee Management Toolkit

Expected Output: A working, modular fee-management script where each function performs one clear job and can be reused independently.

7.13  Interview Questions — Module 7


7.14  Student Notes Page

Use this space to write down key points, doubts, and your own examples from today's session.