Functions
A function in Python is a block (group of program statements) of reusable code that performs
a specific task. You define a function once and can call it multiple times throughout your
program.
It is a named, self-contained block of code that encapsulates a specific task or related
group of tasks, optionally parameterized by inputs (parameters) and optionally returning
a value (or values).
First Class Objects
Parameters
1. Formal Parameter:
1. Identifiers that appear in the function definition.
2. They act as local variables within the function scope.
2. Actual Parameters (Arguments):
1. Values or expressions supplied to the function at the point of call.
2. They are evaluated and passed to the function, where they are bounded to the
formal parameters.
def multiply(x,y):
return x*y
r = multiply(2,4)
x, y are the formal parameters
2, 4 are the arguments
Note: Python uses call-by-object-reference i.e. reference pointers to objects are
passed and not the actual objects or primitive values. Thus mutable types CAN be changed
within the function.
Function Definition
1. Header
2. Docstring: Special string that describes what the function does. Appears right after the
function header.
3. Statements
4. Return
1. return - returns None
Void / Non-Fruitful Function
Non-Void / Fruitful Function
Types of Arguments
Positional
Required Arguments
No of Arguments = No of Parameters
Values assigned to Parameters based on their position in the function call
Default
Parameters can have default values if no argument is provided
Must come after non-default parameters
Keyword
Order doesn't matter
Variable-Length
*args : collects extra positional arguments as a tuple
**kwargs : collects extra keyword arguments as a dictionary
Scope of the Variable
Local
Defined inside a function, only accessible within that function.
Global
Defined outside functions, accessible throughout the program.
global keyword used to access
LEGB: Local, Enclosing, Global, Built-In
Note: Mutable globals can be modified without global
nonlocal
x = 20
def f(a):
print(x)
x = 40
return
f(10)
x = 20
def f(a):
x = 40
return a
y = f(10)
print(x, y)