ICT582 Python Revision
🎯 Learning Objectives
πŸ“š 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
  1. Know the difference between a parameter (definition) and an argument (call).
  2. Functions without return return None β€” assigning the call result to a variable gives None.
  3. Local variables don't exist outside the function β€” a key exam trace question.
  4. Know when to use global keyword (modifying a global inside a function).
  5. Be able to write a function, call it, and trace its output.
❌ Common Mistakes
⚑ Quick Recap
← Topic 05: Data Structures Topic 07: Files & Strings β†’