ЁЯФм
ЁЯзм
ЁЯФн
ЁЯкР
ЁЯзк
тЖР Back to Dashboard
Font Size:

1. Introduction

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.

2. Defining and Calling Functions

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.

2.1 Function with No Arguments

def greet():
    print("Hello, welcome to Python!")

greet()   # Hello, welcome to Python!

2.2 Function Returning Multiple Values

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

3. Types of Arguments

Python is flexible about how arguments are supplied.

3.1 Positional Arguments

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

3.2 Keyword Arguments

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

3.3 Default Arguments

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

3.4 Variable-Length Arguments: args and *kwargs

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

4. Return Value and None

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

5. Scope of Variables

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

6. Passing Mutable and Immutable Arguments

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

7. Lambda Functions

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)]

8. Using Modules

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

Quick Revision Tables

Table 1: Ways to Pass Arguments

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

Table 2: Scope Rules

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

Mind Map

flowchart TD A[Functions] --> B[Defining and Calling] B --> B1[def keyword] B --> B2[return statement] A --> C[Argument Types] C --> C1[Positional] C --> C2[Keyword] C --> C3[Default] C --> C4[args and kwargs] A --> D[Scope] D --> D1[Local variables] D --> D2[Global variables] D --> D3[global keyword] A --> E[Argument Passing] E --> E1[Mutable objects change in place] E --> E2[Immutable objects unaffected] A --> F[Lambda Functions] A --> G[Modules] G --> G1[import] G --> G2[from import] G --> G3[Standard library math random os]

Important Diagrams (SVG)

Diagram 1: Function Call and Return Flow

How a Function Call Works MAIN PROGRAM result = add(5, 3) call 5, 3 FUNCTION add(a, b) return a + b Compute a + b = 8 return 8 result = 8 control returns to caller Golden Rule: Call passes arguments, the function runs, and return hands a value back to the caller.

Diagram 2: Scope of Variables

Global and Local Scope GLOBAL SCOPE x = 10 count = 0 visible everywhere LOCAL SCOPE of demo() y = 5 can read global x y exists only during call reads x global keyword allows modifying a global variable inside a function Golden Rule: Local variables exist only inside their function; global variables need the global keyword to be modified.

Common Mistakes

  1. Forgetting to return a value: A function that prints but does not return gives None when assigned; know the difference between printing and returning.
  2. Calling a function before defining it: The def statement must execute before the call, though in practice functions are defined before use in the source.
  3. Wrong order of default parameters: Parameters with defaults must come after parameters without defaults, or a SyntaxError occurs.
  4. Using a local variable outside its function: Variables inside a function are inaccessible outside; accessing them raises NameError.
  5. Modifying a global without the global keyword: Assigning to a global name inside a function creates a local instead, silently changing behaviour.
  6. Expecting immutable arguments to change: Passing an int or string and reassigning it inside the function does not affect the caller.
  7. Mutating a list argument unintentionally: Lists are passed by reference; changes inside the function alter the caller's list.
  8. Confusing *args with kwargs: *args collects positional arguments into a tuple; kwargs collects keyword arguments into a dictionary.

Exam Tips

  1. Always identify the parameters, arguments and return value when asked to trace a function.
  2. Practise writing functions for standard tasks: sum of digits, factorial, prime check, list operations.
  3. Know the difference between print and return: return hands a value to the caller; print merely displays it.
  4. Memorise the argument types with one example each, including default and *args.
  5. Explain scope with a concrete example and show when the global keyword is required.
  6. State the mutability rule: mutable arguments can be changed inside functions; immutable ones cannot.
  7. Use lambda for small anonymous functions in sorting, and mention its syntax correctly.

Conclusion

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.