A function is a named block of code that performs a specific task and can be called whenever that task is needed. Functions are the primary tool for structuring a program: they eliminate duplicate code, divide large problems into manageable pieces, and make programs easier to read, test and maintain. Python provides many built-in functions such as print(), len(), sum() and range(), and it allows programmers to define their own functions with the def keyword.
A function is defined once and called many times. When a function is called, the interpreter executes its body, optionally using arguments passed by the caller, and optionally returning a result. The use of functions is a cornerstone of good programming practice, and function-based questions form a large part of the board examination, covering definitions, argument passing, scope, the return value, and code-writing with functions.
This chapter revises the mechanics of defining and calling functions, the different ways arguments can be passed, the rules of scope that determine which variables a function can see, and the special constructs lambda, args and *kwargs. It also introduces the standard library modules that supply reusable functions and the concept of an application program interface through module imports.
A function is defined with the def keyword, a name, parentheses, an optional parameter list and a colon. The body, which must be indented, contains the statements executed when the function is called. The return statement sends a value back to the caller and immediately exits the function.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
The name add is the function name, a and b are parameters, and 5 and 3 are the arguments supplied at the call. A function without a return statement returns None by default.
def greet():
print("Hello, welcome to Python!")
greet() # Hello, welcome to Python!
Python functions can return multiple values as a tuple, which is unpacked by the caller.
def min_max(lst):
return min(lst), max(lst)
lo, hi = min_max([4, 9, 2, 7])
print(lo, hi) # 2 9
Python is flexible about how arguments are supplied.
Arguments are matched to parameters in order. The first argument fills the first parameter, the second fills the second, and so on.
def info(name, age):
print(name, "is", age, "years old")
info("Aarav", 17) # Aarav is 17 years old
Arguments can be passed by naming the parameter, which makes the call clearer and allows any order.
info(age=17, name="Aarav") # Aarav is 17 years old
A parameter can have a default value. If the caller omits that argument, the default is used. Default parameters must follow non-default parameters in the definition.
def greet_user(name, greeting="Hello"):
print(greeting + ", " + name)
greet_user("Aarav") # Hello, Aarav
greet_user("Bhavna", "Welcome") # Welcome, Bhavna
The *args parameter collects any number of extra positional arguments into a tuple. The **kwargs parameter collects extra keyword arguments into a dictionary.
def total(*args):
return sum(args)
print(total(1, 2, 3)) # 6
print(total(10, 20)) # 30
def show(**kwargs):
for key, value in kwargs.items():
print(key, value)
show(name="Aarav", marks=92) # name Aarav marks 92
The return statement exits the function and optionally delivers a value. A function that does not return explicitly returns None. The return keyword can appear anywhere in the body; once executed, the remaining statements of the function are skipped.
def check(n):
if n > 0:
return "Positive"
elif n < 0:
return "Negative"
else:
return "Zero"
print(check(-5)) # Negative
Scope determines where a variable is visible. A variable assigned inside a function is local to that function: it exists only while the function runs and cannot be accessed outside. A variable assigned at the top level of a module is global: it is visible everywhere in that module, including inside functions, but assigning to it inside a function creates a new local variable unless the global keyword is used.
x = 10 # global variable
def demo():
y = 5 # local variable
print(x, y) # can read the global
demo() # 10 5
# print(y) -> NameError: y is not defined
To modify a global variable inside a function, declare it global:
count = 0
def increment():
global count
count += 1
increment()
print(count) # 1
Python passes arguments by object reference. If the argument is an immutable type such as a number or string, reassignment inside the function does not affect the caller. If the argument is a mutable type such as a list, modifications made to the object inside the function are visible to the caller.
def change(lst):
lst.append(100) # mutates the caller's list
marks = [50, 60]
change(marks)
print(marks) # [50, 60, 100]
def reassign(n):
n = 99 # does not affect the caller
value = 10
reassign(value)
print(value) # 10
A lambda is a small anonymous function defined with the lambda keyword: lambda parameters: expression. It can be used wherever a simple function is needed, typically with higher-order functions like sorted().
square = lambda x: x * x
print(square(5)) # 25
points = [(1, 3), (2, 1), (3, 2)]
points.sort(key=lambda p: p[1])
print(points) # [(2, 1), (3, 2), (1, 3)]
A module is a file containing Python definitions and statements that can be imported into other programs. The import statement loads a module, and functions of the module are accessed with dot notation.
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
from math import factorial, gcd
print(factorial(5)) # 120
print(gcd(12, 18)) # 6
Common standard library modules include math (mathematical functions), random (random numbers), os (operating system functions) and datetime (date and time).
import random
print(random.randint(1, 10)) # a random integer between 1 and 10
| Type | Example Call | Behaviour |
|---|---|---|
| Positional | info("Aarav", 17) | Matched by position |
| Keyword | info(age=17, name="Aarav") | Matched by parameter name |
| Default | greet_user("Aarav") | Uses default value |
| *args | total(1, 2, 3) | Collects extra positional args in a tuple |
| **kwargs | show(name="Aarav") | Collects extra keyword args in a dict |
| Variable | Where Defined | Visible? |
|---|---|---|
| Local | Inside a function | Only inside that function |
| Global | Top level of module | Everywhere in the module |
| Function parameter | In the function definition | Inside the function |
Functions transform a flat script into an organised, reusable program. Defining a function with def, supplying arguments by position or name, using defaults and variable-length arguments, and returning values are the fundamental mechanics. Scope rules control which variables a function can see, and the mutable versus immutable distinction determines how arguments behave. Lambda functions provide compact anonymous functions, and modules extend the language with reusable libraries. Functions are also the gateway to recursion, because a function that calls itself creates the elegant recursive solutions of the next chapter.