⬅ Previous Next ➡

Functions and Modules

Defining Functions (Basics)
  • Function = reusable block of code.
  • Defined using def keyword.
  • Helps reduce repetition and improves readability.
def greet():
    print("Hello, Python")

greet()
Function Arguments (Parameters)
  • Arguments pass data to a function.
  • Common types: positional, keyword, default, variable-length.
# Positional arguments
def add(a, b):
    print(a + b)

add(10, 20)

# Keyword arguments
add(b=5, a=2)

# Default arguments
def welcome(name="Guest"):
    print("Welcome", name)

welcome()
welcome("Sourav")

# Variable-length arguments (*args)
def total_sum(*nums):
    print(sum(nums))

total_sum(1, 2, 3, 4)
Return Values
  • return sends value back to the caller.
  • Function ends immediately after return.
  • Can return multiple values (as tuple).
def square(n):
    return n * n

ans = square(5)
print(ans)

def calc(a, b):
    return a + b, a - b

addv, subv = calc(10, 3)
print(addv, subv)
Lambda Function (Anonymous Function)
  • Short function written in one line using lambda.
  • Used for quick operations (often with map/filter/sort).
square = lambda x: x * x
print(square(6))

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

nums = [1, 2, 3, 4]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even)
Recursion (Function Calling Itself)
  • Recursion = function calls itself.
  • Must have a base condition to stop recursion.
  • Used in factorial, Fibonacci, tree problems, etc.
def factorial(n):
    if n == 0 or n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))   # 120
Scope of Variables (Local and Global)
  • Local: defined inside a function (only usable inside).
  • Global: defined outside function (usable everywhere).
  • Use global keyword to modify global variable inside function.
x = 10   # global

def show():
    x = 5    # local
    print("Inside:", x)

show()
print("Outside:", x)

def change():
    global x
    x = 99

change()
print("After change:", x)
Modules (Importing and Using)
  • Module = a Python file with functions, variables, classes.
  • Used to organize code and reuse functionality.
  • Use import to include a module.
import math

print(math.sqrt(25))
print(math.pi)

from math import factorial
print(factorial(5))

import math as m
print(m.pow(2, 3))
Built-in Modules (Examples)
  • math → math operations
  • random → random numbers
  • datetime → date & time
  • os → operating system tasks
  • sys → system-specific parameters
import random
import datetime

print(random.randint(1, 10))
print(datetime.datetime.now())
Custom Module (User-Defined Module)
  • Create your own module as a .py file.
  • Import it like built-in modules.
File: mymath.py
def add(a, b):
    return a + b

def sub(a, b):
    return a - b
File: main.py
import mymath

print(mymath.add(10, 5))
print(mymath.sub(10, 5))
⬅ Previous Next ➡