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 greet(name):return f"Hello, {name}!"message = greet("Aanya") # call it → "Hello, Aanya!"# Parameters are inputs; return is the outputdef area(width, height):return width * heightarea(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:
def counter():total = 0 # local — cannot be seen outsidereturn total# print(total) # ERROR — total doesn't exist herex = 10 # globaldef show():print(x) # can READ a globalshow() # 10
Key takeaways
- 01def defines a function; parameters are inputs, return is the output.
- 02Functions remove duplication (DRY) and give logic a readable name.
- 03Variables created inside a function are local to that call.
- 04A function can read globals but its locals are invisible outside.
- 05A function with no return yields None.
