Working with Functions in Python Class 12 Notes

Last updated on May 27th, 2026 at 09:31 am

📌 Unit — Functions in Python | Class 11 & 12 Computer Science (083)
Topics covered: What is a function, types of functions, defining & calling, arguments & parameters, types of arguments (positional, keyword, default, variable-length), return statement, scope of variables (local, global), global keyword, lambda functions — with complete programs and MCQs.

1. What is a Function?

A function is a named block of code that performs a specific task. It runs only when called. Functions help break a large program into smaller, reusable, and organized pieces.

FunctionA group of related statements that perform a specific task. It runs only when called. Can accept inputs (parameters) and return an output (return value).

Why Use Functions?

  • Code Reusability: Write once, use many times — no need to repeat the same code.
  • Modularity: Break large programs into small manageable parts.
  • Easy Debugging: Errors are easier to find and fix in small functions.
  • Readability: Program becomes more organized and easy to understand.
  • Avoid Duplication: Reduces redundant code in the program.

2. Types of Functions in Python

TypeDescriptionExamples
Built-in FunctionsPre-defined in Python — always available, no import neededprint(), input(), len(), type(), int(), range(), min(), max()
Functions in ModulesDefined in modules/libraries — must import firstmath.sqrt(), random.randint(), datetime.date.today()
User Defined FunctionsCreated by the programmer using def keyworddef add(), def greet(), def calculate_area()
Lambda FunctionsSmall anonymous (no name) single-line functionslambda x: x*2

3. User Defined Functions — Syntax

def function_name(parameters):
    """docstring — optional description of function"""
    statement(s)
    return value     # optional
defKeyword used to define a function. Must be followed by function name and parentheses.
function_nameName of the function — follows same rules as identifiers. Should be meaningful.
parametersVariables listed inside parentheses — receive values when function is called. Optional.
docstringOptional string to describe what the function does. Written in triple quotes.
returnOptional statement to send a value back to the calling code.

Defining and Calling a Function

# DEFINING the function
def greet():
    print("Hello! Welcome to cbsepython.in")

# CALLING the function
greet()
greet()    # can be called multiple times
Hello! Welcome to cbsepython.in Hello! Welcome to cbsepython.in
Function define karne se kuch nahi hota — calling ke baad hi execute hota hai. Function ek baar define karo, hazaar baar call karo!

4. Arguments and Parameters

TermWhereExample
ParameterIn function DEFINITION — receives valuedef add(a, b): — here a, b are parameters
ArgumentIn function CALL — value passedadd(5, 3) — here 5, 3 are arguments
def welcome(name):      # 'name' is PARAMETER
    print("Hello,", name)

welcome("Rahul")        # "Rahul" is ARGUMENT
welcome("Priya")
Hello, Rahul Hello, Priya
Parameter = function definition mein. Argument = function call mein. Dono ke beech yahi difference hai — board exam mein zaroor poocha jaata hai.

5. Four Types of Functions (Based on Arguments & Return)

i) No Argument, No Return

def add():
    a = int(input("Num1: "))
    b = int(input("Num2: "))
    print("Sum:", a+b)
add()

Input inside function. Output printed inside function.

ii) With Argument, No Return

def add(a, b):
    print("Sum:", a+b)
x = int(input("Num1: "))
y = int(input("Num2: "))
add(x, y)

Values passed from outside. Result printed inside.

iii) No Argument, With Return

def add():
    a = int(input("Num1: "))
    b = int(input("Num2: "))
    return a + b
result = add()
print("Sum:", result)

Input inside function. Result returned and stored outside.

iv) With Argument, With Return

def add(a, b):
    return a + b
x = int(input("Num1: "))
y = int(input("Num2: "))
result = add(x, y)
print("Sum:", result)

Values passed in, result returned. Most flexible type.

6. Types of Arguments in Python

Type 1 — Positional Arguments (Required Arguments)

Arguments passed in the same order as parameters defined. Number must match exactly.

def student(name, roll, marks):
    print(f"Name: {name}, Roll: {roll}, Marks: {marks}")

student("Rahul", 101, 85)   # positional — order matters!
Name: Rahul, Roll: 101, Marks: 85
Positional arguments mein order ZAROORI hai. student(101, “Rahul”, 85) galat result dega!

Type 2 — Keyword Arguments (Named Arguments)

Arguments passed by name — order does not matter.

def student(name, roll, marks):
    print(f"Name: {name}, Roll: {roll}, Marks: {marks}")

student(roll=101, marks=85, name="Rahul")   # order doesn't matter!
Name: Rahul, Roll: 101, Marks: 85

Type 3 — Default Arguments

Parameters with a default value — if no argument passed, default is used.

def greet(name, msg="Good Morning"):   # msg has default value
    print(f"Hello {name}! {msg}")

greet("Rahul")                          # uses default msg
greet("Priya", "Good Evening")         # overrides default
Hello Rahul! Good Morning Hello Priya! Good Evening
Default arguments HAMESHA end mein likhte hain. def greet(msg=”Hi”, name) — yeh GALAT hai! Default parameters non-default parameters ke baad hi aane chahiye.

Type 4 — Variable Length Arguments (*args)

When you don’t know how many arguments will be passed — use *args. Receives all arguments as a tuple.

def add_all(*nums):              # *args — any number of values
    total = 0
    for n in nums:
        total += n
    print("Sum:", total)
    print("Type:", type(nums))

add_all(1, 2, 3)
add_all(10, 20, 30, 40, 50)
Sum: 6 Type: <class ‘tuple’> Sum: 150 Type: <class ‘tuple’>

Types of Arguments — Comparison

TypeSyntaxKey PointExample Call
Positionaldef f(a, b)Order must matchf(10, 20)
Keyworddef f(a, b)Use name=value, order freef(b=20, a=10)
Defaultdef f(a, b=5)Default used if not passedf(10) or f(10, 3)
Variable (*args)def f(*nums)Any number, stored as tuplef(1,2,3,4,5)

7. return Statement

The return statement sends a value back from the function to the calling code. It does not print — you must store or print the returned value.

def square(n):
    return n * n          # returns value, does NOT print

result = square(5)
print(result)            # 25
print(square(7))         # 49 — directly in print
25 49

Returning Multiple Values

Python functions can return multiple values as a tuple.

def min_max(lst):
    return min(lst), max(lst)   # returns tuple

lo, hi = min_max([4, 1, 9, 2, 7])
print("Min:", lo, "Max:", hi)
Min: 1 Max: 9
return ke baad function turant khatam ho jaata hai — uske baad koi bhi code execute nahi hota. return ke baad wala code unreachable code kehlata hai.

8. Scope of Variables — Local and Global

Scope refers to the region of a program where a variable is accessible.

TypeDefined WhereAccessible WhereLifetime
Local VariableInside a functionOnly inside that functionUntil function ends
Global VariableOutside all functions (main program)Everywhere — inside and outside functionsEntire program

Local Variable Example

def myFunc():
    x = 10               # x is LOCAL — only inside myFunc
    print("Inside:", x)

myFunc()
print(x)                # ERROR! x not accessible outside
Inside: 10 NameError: name ‘x’ is not defined

Global Variable Example

school = "CBSE Python School"    # GLOBAL variable

def display():
    print(school)               # accessible inside function

display()
print(school)                   # accessible outside too
CBSE Python School CBSE Python School

Same Name — Local and Global

x = 100                  # global x

def test():
    x = 50                # local x — DIFFERENT from global x
    print("Inside:", x)   # 50 (local)

test()
print("Outside:", x)     # 100 (global unchanged)
Inside: 50 Outside: 100

9. global Keyword

By default, a variable inside a function is local. To modify a global variable inside a function, use the global keyword.

count = 0                 # global variable

def increment():
    global count           # declare we want to use global count
    count += 1             # modifying global variable
    print("Count:", count)

increment()
increment()
increment()
print("Final:", count)
Count: 1 Count: 2 Count: 3 Final: 3
# Without global keyword — ERROR!
count = 0
def increment():
    count += 1             # UnboundLocalError!
global keyword ke bina function ke andar global variable modify karne par UnboundLocalError aata hai. Sirf read karna ho toh global likhne ki zaroorat nahi — sirf modify karne ke liye chahiye.

10. Lambda Functions (Anonymous Functions)

A lambda function is a small, anonymous (no name) function defined in a single line using the lambda keyword.

# Syntax:
lambda parameters : expression

# Example — square a number:
square = lambda x : x * x
print(square(5))     # 25

# Lambda with two parameters:
add = lambda a, b : a + b
print(add(3, 4))     # 7

# Lambda for checking even/odd:
is_even = lambda n : "Even" if n % 2 == 0 else "Odd"
print(is_even(6))    # Even
print(is_even(7))    # Odd
25 7 Even Odd

Lambda vs Normal Function

Featuredef FunctionLambda Function
NameHas a nameAnonymous (no name needed)
LinesMultiple lines possibleSingle expression only
returnUses return keywordAutomatically returns expression
docstringCan have docstringCannot have docstring
Use caseComplex functionsShort, simple one-line operations
Lambda function ek hi line mein hota hai aur automatically value return karta hai. return keyword nahi likhte. Board exam mein lambda ka syntax aur ek simple program zaroor aata hai.

11. Complete Programs

Program 1 — Factorial using Function

def factorial(n):
    fact = 1
    for i in range(1, n+1):
        fact *= i
    return fact

num = int(input("Enter number: "))
print(f"Factorial of {num} is:", factorial(num))
Enter number: 5 Factorial of 5 is: 120

Program 2 — Check Prime using Function

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

n = int(input("Enter number: "))
if is_prime(n):
    print(n, "is Prime")
else:
    print(n, "is Not Prime")
Enter number: 7 7 is Prime

Program 3 — Default Argument — Area of Rectangle

def area(length, breadth=10):     # breadth has default value
    return length * breadth

print("Area 1:", area(5))         # breadth = 10 (default)
print("Area 2:", area(5, 8))      # breadth = 8 (given)
Area 1: 50 Area 2: 40

Program 4 — *args — Sum of Any Numbers

def total(*nums):
    s = sum(nums)
    print(f"Numbers: {nums}")
    print(f"Sum: {s}, Average: {s/len(nums):.2f}")

total(10, 20, 30)
total(5, 15, 25, 35, 45)
Numbers: (10, 20, 30) Sum: 60, Average: 20.00 Numbers: (5, 15, 25, 35, 45) Sum: 125, Average: 25.00

Program 5 — global Keyword Usage

total_students = 0

def add_student(name):
    global total_students
    total_students += 1
    print(f"Added: {name} | Total: {total_students}")

add_student("Rahul")
add_student("Priya")
add_student("Ajay")
print("Final count:", total_students)
Added: Rahul | Total: 1 Added: Priya | Total: 2 Added: Ajay | Total: 3 Final count: 3

Program 6 — Lambda — Sort by Second Element

students = [("Rahul", 85), ("Priya", 92), ("Ajay", 74)]

# Sort by marks (2nd element) using lambda
students.sort(key=lambda x: x[1], reverse=True)

for s in students:
    print(f"{s[0]:<10} {s[1]}")
Priya 92 Rahul 85 Ajay 74

12. Practice MCQs — Board Exam Style

Q1. Which keyword is used to define a function in Python?

a) function   b) define   c) def   d) func
✅ Answer: c) def — used to mark the beginning of a function definition. Example: def myFunc():

Q2. What is the difference between a parameter and an argument?

a) Both are same   b) Parameter is in function call, argument in definition   c) Parameter is in function definition, argument is in function call   d) None of above
✅ Answer: c) Parameter is in function DEFINITION. Argument is in function CALL. def add(a,b) — a,b are parameters. add(5,3) — 5,3 are arguments.

Q3. What type does *args store multiple values as?

a) List   b) Dictionary   c) Tuple   d) Set
✅ Answer: c) Tuple — *args stores all extra positional arguments as a tuple inside the function.

Q4. Which of the following is a correct definition with default argument?

a) def f(a=5, b)   b) def f(b, a=5)   c) def f(=5, b)   d) def f(a, 5=b)
✅ Answer: b) def f(b, a=5) — default arguments must come AFTER non-default arguments. def f(a=5, b) is a SyntaxError.

Q5. A variable defined inside a function is called:

a) Global variable   b) Local variable   c) Static variable   d) Public variable
✅ Answer: b) Local variable — accessible only inside the function where it is defined.

Q6. To modify a global variable inside a function, which keyword is used?

a) local   b) var   c) global   d) extern
✅ Answer: c) global — write “global variable_name” at the start of the function before modifying it.

Q7. What is the output?
f = lambda x, y: x if x > y else y
print(f(10, 20))

a) 10   b) 20   c) True   d) Error
✅ Answer: b) 20 — the lambda returns the larger of x and y. 10 > 20 is False, so y (20) is returned.

Q8. What happens after a return statement executes in a function?

a) Function continues   b) Function immediately ends   c) return is ignored   d) Error occurs
✅ Answer: b) Function immediately ends — any code after return is not executed (unreachable code).

Q9. Which type of argument allows passing arguments by name regardless of position?

a) Positional   b) Default   c) Keyword   d) Variable length
✅ Answer: c) Keyword arguments — call like: f(name=”Rahul”, age=17). Order doesn’t matter.

Q10. What will be the output?
def show(a, b=10, c=20):
    print(a, b, c)
show(5, c=30)

a) 5 10 20   b) 5 10 30   c) 5 30 20   d) Error
✅ Answer: b) 5 10 30 — a=5 (positional), b=10 (default), c=30 (keyword argument overrides default).

📚 More Notes: Text File Handling  |  Binary File Handling  |  All Class 12 MCQs  |  All Class 12 Notes

Copywrite © 2020-2026, CBSE Python,
All Rights Reserved