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
- Python executes top-to-bottom
- Function definition is registered, not executed
- At call site: control jumps to function body
- After
return(or end of body): control returns to caller - Return value is substituted at call site
02
Unit 8
Types of Function Arguments
| Type | Syntax | Example |
|---|---|---|
| Required (Positional) | Normal params | def f(a, b) → f(1, 2) |
| Keyword | Name=value at call | f(b=2, a=1) |
| Default | Param with default | def f(a, b=10) |
| Variable-length (*args) | *args | Tuple of extra positionals |
| Variable keyword (**kwargs) | **kwargs | Dict 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 → **kwargs03
Unit 9
Scope & Lifetime of Variables
| Scope | Where Defined | Accessible |
|---|---|---|
| Local | Inside function | Only inside that function |
| Enclosing | Outer function (nested) | Inner function |
| Global | Module level | Everywhere in module |
| Built-in | Python builtins | Everywhere |
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 →
RecursionErrorLambda (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
| Module | Key Functions |
|---|---|
math | sqrt, floor, ceil, pow, log, factorial, pi, e |
random | random(), randint(), choice(), shuffle(), seed() |
os | getcwd(), listdir(), path.join(), mkdir() |
sys | argv, path, exit(), version |
datetime | date.today(), datetime.now(), timedelta |
FC
Quick Review
Flashcards — Module II
Tap to flip