MODULE 02 · ← All Modules
FUNCTIONS & MODULES
01
Unit 7

Function Definition, Calling & Flow

A function is a named, reusable block of code. Benefits: modularity, code reuse, readability, easier debugging.
# Definition
def greet(name):          # name = parameter
    """Docstring here"""
    return f"Hello, {name}!"

# Calling
msg = greet("Aswin")      # "Aswin" = argument
print(msg)               # Hello, Aswin!

Flow of Execution

  1. Python executes top-to-bottom
  2. Function definition is registered, not executed
  3. At call site: control jumps to function body
  4. After return (or end of body): control returns to caller
  5. Return value is substituted at call site
02
Unit 8

Types of Function Arguments

TypeSyntaxExample
Required (Positional)Normal paramsdef f(a, b)f(1, 2)
KeywordName=value at callf(b=2, a=1)
DefaultParam with defaultdef f(a, b=10)
Variable-length (*args)*argsTuple of extra positionals
Variable keyword (**kwargs)**kwargsDict of extra keyword args
# *args and **kwargs together
def demo(*args, **kwargs):
    print(args)    # tuple: (1, 2, 3)
    print(kwargs)  # dict:  {'x': 10, 'y': 20}

demo(1, 2, 3, x=10, y=20)

# Default args — mutable default trap!
def bad(lst=[]):      # ⚠ shared across calls
    lst.append(1); return lst
def good(lst=None):  # ✓ correct pattern
    if lst is None: lst = []
    lst.append(1); return lst
Default argument order: required → default → *args → **kwargs
03
Unit 9

Scope & Lifetime of Variables

ScopeWhere DefinedAccessible
LocalInside functionOnly inside that function
EnclosingOuter function (nested)Inner function
GlobalModule levelEverywhere in module
Built-inPython builtinsEverywhere

Lookup order: LEGB — Local → Enclosing → Global → Built-in

# global keyword
x = 10
def modify():
    global x
    x = 20   # modifies global x

# nonlocal keyword (nested functions)
def outer():
    y = 5
    def inner():
        nonlocal y
        y = 10
    inner()
    print(y)  # 10
Lifetime: Local variables are created when function is called and destroyed when it returns.
04
Unit 10

Recursive, Lambda & Special Functions

Recursion

def factorial(n):
    if n == 0: return 1       # base case
    return n * factorial(n-1) # recursive case

# Fibonacci
def fib(n):
    if n <= 1: return n
    return fib(n-1) + fib(n-2)
Every recursion needs: (1) Base case to stop, (2) Recursive case that moves toward base case. Without base case → infinite recursion → RecursionError

Lambda (Anonymous Function)

# lambda args: expression
square = lambda x: x**2
add    = lambda a,b: a+b

# Useful with higher-order functions
nums = [3,1,4,1,5,9]
sorted(nums, key=lambda x: -x)   # descending
list(map(lambda x: x*2, nums))   # double each
list(filter(lambda x: x%2==0, nums)) # evens only

Multiple Return Values & Void

# Multiple return — returns a tuple
def min_max(lst):
    return min(lst), max(lst)

lo, hi = min_max([3,1,4,5])  # unpacking

# Void function — returns None implicitly
def say_hi():
    print("Hi")           # no return statement
05
Unit 11

Built-in Modules & User-Defined Packages

# Import styles
import math
from math import sqrt, pi
from math import *        # import everything (avoid)
import math as m          # alias

# User-defined module (myutils.py)
def add(a, b): return a+b

# In another file:
import myutils
myutils.add(3, 4)

Package Structure

mypackage/
  __init__.py      # makes it a package
  module1.py
  module2.py

from mypackage import module1
from mypackage.module2 import some_function

Common Built-in Modules

ModuleKey Functions
mathsqrt, floor, ceil, pow, log, factorial, pi, e
randomrandom(), randint(), choice(), shuffle(), seed()
osgetcwd(), listdir(), path.join(), mkdir()
sysargv, path, exit(), version
datetimedate.today(), datetime.now(), timedelta
FC
Quick Review

Flashcards — Module II

Tap to flip