Functions: Reusable Blocks of Code
Packaging Code into Functions
A function is a named block of code that performs one job. You write it once and then call it whenever you need it. Functions keep programs short, organised, and easy to fix.
Defining a Function
Use the def keyword, give the function a name, and add parentheses. The indented lines below form the function body.
def greet():
print("Hello from DCCPS!")
greet() # this line calls the functionDefining a function does not run it. Nothing happens until you call it by writing its name followed by parentheses.
Parameters and Arguments
A parameter is an input listed when you define the function. An argument is the real value you pass when you call it.
def greet(name):
print(f"Hello, {name}!")
greet("Ayesha") # name becomes "Ayesha"
greet("Rahim") # name becomes "Rahim"Returning a Value
The return keyword sends a result back to whoever called the function. The caller can store that result in a variable.
def add(x, y):
return x + y
result = add(8, 5)
print(result) # 13
print(add(100, 1)) # 101There is a difference between print and return. print only displays text on screen. return hands back a value your program can keep using.
Default Parameter Values
You can give a parameter a default so the argument becomes optional.
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25 uses default exponent 2
print(power(5, 3)) # 125 exponent given as 3Why Functions Matter
- They remove repetition — write the logic once.
- They make code readable — a good name explains intent.
- They make bugs easy to fix — correct one place, not many.
A function should do one clear thing. If you struggle to name it, it may be doing too much — split it into smaller functions.
Discussion
0No comments yet — be the first to leave one!