Topic 06 of 12 | π Lecture 6 β ICT582Topic06.pdf
Functions & Modules
Define reusable code blocks, understand scope, and use Python modules.
π― Learning Objectives
- Define and call functions using
def - Use positional and keyword arguments; define default parameter values
- Return values from functions using
return - Explain local vs global scope
- Write lambda (anonymous) functions
- Import and use standard modules (
math,random) - Understand why functions promote code reuse (divide-and-conquer)
π Key Concepts
Defining a Function
def greet(name):
# name is a parameter (local to this function)
message = "Hello, " + name + "!"
return message
result = greet("Alice") # "Alice" is an argument
print(result) # Hello, Alice!
Functions must be defined before they are called.
Parameters, Arguments, and Defaults
# Default parameter value
def power(base, exp=2): # exp defaults to 2
return base ** exp
print(power(3)) # 9 (uses default exp=2)
print(power(3, 3)) # 27 (overrides default)
# Keyword argument
print(power(exp=3, base=2)) # 8 (order doesn't matter)
Return Statement
A function without return returns None. You can return multiple values as a tuple.
def min_max(numbers):
return min(numbers), max(numbers) # returns tuple
lo, hi = min_max([5, 2, 8, 1, 9])
print(lo, hi) # 1 9
Scope: Local vs Global
A variable created inside a function is local β it only exists inside that function. A variable created outside is global.
x = 10 # global
def show():
y = 20 # local to show()
print(x) # can read global x
print(y) # 20
show()
print(y) # NameError! y doesn't exist outside
# To modify a global variable inside a function:
count = 0
def increment():
global count
count += 1
Lambda Functions
A short anonymous function β one expression only. Good for simple operations.
square = lambda x: x ** 2
print(square(5)) # 25
add = lambda a, b: a + b
print(add(3, 4)) # 7
# Useful with built-ins like sorted()
pairs = [(1, 'b'), (3, 'a'), (2, 'c')]
pairs.sort(key=lambda p: p[1])
print(pairs) # [(3,'a'), (1,'b'), (2,'c')]
Importing Modules
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.14159...
print(math.floor(3.7)) # 3
print(math.ceil(3.2)) # 4
import random
print(random.randint(1, 6)) # random int 1β6
print(random.random()) # random float 0β1
random.shuffle([1,2,3,4,5]) # shuffle in place
# Import specific names
from math import sqrt, pi
print(sqrt(25)) # 5.0 (no math. prefix needed)
Creating Your Own Module
Any .py file is a module. Save functions in myutils.py, then import myutils in another file.
# myutils.py
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
# main.py
import myutils
print(myutils.celsius_to_fahrenheit(100)) # 212.0
π» Code Examples
Example 1 β Function with multiple parameters
def grade(score, total=100):
pct = score / total * 100
if pct >= 80: return "HD"
elif pct >= 70: return "D"
elif pct >= 60: return "C"
elif pct >= 50: return "P"
else: return "N"
print(grade(75)) # D
print(grade(18, 25)) # D (18/25 = 72%)
Example 2 β Recursive function
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120
β οΈ Exam Focus
- Know the difference between a parameter (definition) and an argument (call).
- Functions without
returnreturnNoneβ assigning the call result to a variable givesNone. - Local variables don't exist outside the function β a key exam trace question.
- Know when to use
globalkeyword (modifying a global inside a function). - Be able to write a function, call it, and trace its output.
β Common Mistakes
- Calling a function before it's defined β Python reads top to bottom.
- Forgetting
returnβ the function runs but gives backNone. - Trying to modify a global variable without the
globalkeyword β creates a local copy instead. - Confusing
print()withreturnβprintshows output but doesn't give back a value.
β‘ Quick Recap
def name(params):defines a function; call it withname(args).return valuesends a result back; noreturnβNone.- Local variables only exist inside their function.
- Default parameters make arguments optional:
def f(x, y=10). import mathfor maths functions;import randomfor randomness.- Lambda:
f = lambda x: x*2β short anonymous function.