Skip to main content
Albero Academy

Defining Functions

Package reusable logic with def, and understand scope.

Functions11 min

A function is a named, reusable block of code. You define it once and call it as many times as you like. Functions are the single most important tool for organising programs: they remove duplication, give logic a meaningful name, and make code testable.

Defining & calling

Define with def, a name, parameters in parentheses, and an indented body. Call it by name with arguments:

def
def greet(name):
return f"Hello, {name}!"
message = greet("Aanya") # call it → "Hello, Aanya!"
# Parameters are inputs; return is the output
def area(width, height):
return width * height
area(3, 4) # 12

Why functions matter

The principle is DRY — Don't Repeat Yourself. If you find yourself copying the same few lines, wrap them in a function and call it. A change then happens in one place, not ten. Functions also make code readable: calculate_tax(income) says what it does.

Scope

Variables created inside a function are local — they exist only during the call and are invisible outside:

local vs global
def counter():
total = 0 # local — cannot be seen outside
return total
# print(total) # ERROR — total doesn't exist here
x = 10 # global
def show():
print(x) # can READ a global
show() # 10

Key takeaways

  1. 01def defines a function; parameters are inputs, return is the output.
  2. 02Functions remove duplication (DRY) and give logic a readable name.
  3. 03Variables created inside a function are local to that call.
  4. 04A function can read globals but its locals are invisible outside.
  5. 05A function with no return yields None.

Finished this chapter?

Mark it complete to track your progress through Python.