Every time you write print(), len(), or np.mean(), you are calling a function. Functions are the building blocks of every Python program — including the AI programs in your practical file. This guide teaches you how they work and how to write your own.
What You’ll Learn
- What a function is and why you need them
- How to define functions with
defand call them - Parameters, arguments, and return values explained clearly
- Scope — what variables live where
- Lambda functions and when they appear in AI programs
What Is a Function?
A function is a named block of code that performs a specific task. You write it once, then call it by name whenever you need it — instead of rewriting the same code repeatedly.
Think of it like a recipe card. The recipe (function definition) sits in your notebook. Whenever you want to cook that dish, you follow the card (call the function). You don’t rewrite the recipe every time.
python
# Without a function — repetitive code
marks1 = [85, 90, 78]
avg1 = sum(marks1) / len(marks1)
print("Class A average:", avg1)
marks2 = [72, 68, 91, 85]
avg2 = sum(marks2) / len(marks2)
print("Class B average:", avg2)
# With a function — write once, use many times
def calculate_average(marks):
return sum(marks) / len(marks)
print("Class A average:", calculate_average([85, 90, 78]))
print("Class B average:", calculate_average([72, 68, 91, 85]))
Both approaches give the same result. The function version is shorter, easier to read, and if the formula changes, you fix it in one place.
Part 1 — Defining and Calling Functions
Basic Syntax
python
def function_name(parameters):
# code block
return value # optional
def— keyword that starts a function definitionfunction_name— you choose this; use lowercase with underscoresparameters— inputs the function needs (can be empty)return— sends a value back to the caller (optional)
Function With No Parameters
python
# Program to define and call a simple function
def greet():
print("Welcome to CBSE AI!")
print("Let's learn Python together.")
# Call the function
greet()
greet() # call it again — same output, no code rewritten
Expected Output:
Welcome to CBSE AI!
Let's learn Python together.
Welcome to CBSE AI!
Let's learn Python together.
Part 2 — Parameters and Arguments
A parameter is the variable name in the function definition. An argument is the actual value you pass when calling the function.
python
# Program to demonstrate parameters and arguments
def greet_student(name): # 'name' is the parameter
print(f"Hello, {name}! Welcome to AI class.")
greet_student("Arjun") # "Arjun" is the argument
greet_student("Priya")
greet_student("Kiran")
Expected Output:
Hello, Arjun! Welcome to AI class.
Hello, Priya! Welcome to AI class.
Hello, Kiran! Welcome to AI class.
Multiple Parameters
python
# Program to calculate simple interest using a function
def simple_interest(principal, rate, time):
si = (principal * rate * time) / 100
return si
# Call with different values
si1 = simple_interest(2000, 4.5, 10)
si2 = simple_interest(5000, 6, 3)
print("SI for ₹2000 at 4.5% for 10 years:", si1)
print("SI for ₹5000 at 6% for 3 years :", si2)
Expected Output:
SI for ₹2000 at 4.5% for 10 years: 900.0
SI for ₹5000 at 6% for 3 years : 900.0
Default Parameters
Default parameters have a preset value used when no argument is provided:
python
# Program demonstrating default parameter values
def display_grade(marks, passing_marks=33):
if marks >= passing_marks:
print(f"Marks: {marks} — Pass (passing mark: {passing_marks})")
else:
print(f"Marks: {marks} — Fail (passing mark: {passing_marks})")
display_grade(85) # uses default passing_marks=33
display_grade(28) # uses default passing_marks=33
display_grade(28, 25) # overrides default with 25
Expected Output:
Marks: 85 — Pass (passing mark: 33)
Marks: 28 — Fail (passing mark: 33)
Marks: 28 — Pass (passing mark: 25)
Part 3 — Return Values
return sends a value back from the function to wherever it was called. Without return, the function does its job but gives nothing back.
python
# Program to demonstrate return values
def square(number):
return number ** 2
def cube(number):
return number ** 3
def is_even(number):
return number % 2 == 0 # returns True or False
# Use the returned values
x = 7
print(f"Square of {x}:", square(x))
print(f"Cube of {x} :", cube(x))
print(f"Is {x} even? :", is_even(x))
# Store returned value in a variable
result = square(12)
print("Square of 12 stored:", result)
Expected Output:
Square of 7: 49
Cube of 7 : 343
Is 7 even? : False
Square of 12 stored: 144
Returning Multiple Values
Python functions can return more than one value — they come back as a tuple:
python
# Program to return multiple values from a function
def get_stats(data):
minimum = min(data)
maximum = max(data)
average = sum(data) / len(data)
return minimum, maximum, average # returns a tuple
marks = [72, 85, 91, 68, 78, 95, 88]
low, high, avg = get_stats(marks) # tuple unpacking
print(f"Minimum : {low}")
print(f"Maximum : {high}")
print(f"Average : {avg:.2f}")
Expected Output:
Minimum : 68
Maximum : 95
Average : 82.43
Part 4 — Scope: Where Variables Live
Scope determines where a variable can be accessed. This is one of the most misunderstood concepts in Python.
- Local variable — defined inside a function; only accessible within that function
- Global variable — defined outside all functions; accessible everywhere
python
# Program to demonstrate variable scope
total = 100 # global variable
def calculate_discount(price):
discount = 0.10 # local variable — only exists inside this function
final = price - (price * discount)
return final
result = calculate_discount(80)
print("Final price:", result)
print("Total (global):", total)
# print(discount) # NameError — 'discount' is local, not visible here
Expected Output:
Final price: 72.0
Total (global): 100
The rule: If you try to use a variable outside the function where it was defined, Python raises a NameError. Keep your variables local whenever possible — it prevents accidental changes to data in other parts of your program.
Part 5 — Lambda Functions
A lambda is a small, one-line anonymous function. It is defined with the lambda keyword instead of def.
python
# Syntax: lambda parameters: expression
# Regular function
def square(x):
return x ** 2
# Equivalent lambda
square_lambda = lambda x: x ** 2
print(square(5)) # 25
print(square_lambda(5)) # 25
Lambda functions are commonly used with apply() in Pandas — you have already seen this in the Pandas tutorial:
python
import pandas as pd
data = {"Name": ["Arjun","Priya","Kiran"], "Marks": [85, 92, 78]}
df = pd.DataFrame(data)
# Add a Grade column using lambda
df["Grade"] = df["Marks"].apply(lambda x: "A" if x >= 90 else "B" if x >= 75 else "C")
print(df)
Expected Output:
Name Marks Grade
0 Arjun 85 B
1 Priya 92 A
2 Kiran 78 B
Use lambda for short, single-use transformations. Use def for anything longer or reused.
Part 6 — Built-in Functions You Use Every Day
You have been using functions since Class 9 without thinking about it. Here are the most common ones:
| Function | What It Does | Example |
|---|---|---|
print() | Displays output | print("Hello") |
input() | Gets user input | x = input("Enter: ") |
int() | Converts to integer | int("42") → 42 |
float() | Converts to float | float("3.14") → 3.14 |
str() | Converts to string | str(42) → “42” |
len() | Length of sequence | len([1,2,3]) → 3 |
range() | Generates number sequence | range(1, 6) |
sum() | Sum of iterable | sum([1,2,3]) → 6 |
min() | Minimum value | min([5,2,8]) → 2 |
max() | Maximum value | max([5,2,8]) → 8 |
round() | Rounds a number | round(3.14159, 2) → 3.14 |
type() | Data type of a value | type(42) → <class 'int'> |
Quick Revision Box
| Term | Meaning |
|---|---|
def | Keyword used to define a function |
| Parameter | Variable name in the function definition |
| Argument | Actual value passed when calling the function |
return | Sends a value back from the function to the caller |
| Default parameter | A parameter with a preset value used if no argument is given |
| Local variable | Defined inside a function — only accessible within it |
| Global variable | Defined outside all functions — accessible everywhere |
lambda | A short anonymous one-line function |
| Function call | Using the function by name with () — e.g., greet() |
Practice Questions
Q1 (2 marks): Write a Python function calculate_area(length, breadth) that returns the area of a rectangle. Call it with length = 10 and breadth = 5 and print the result.
Model Answer:
python
def calculate_area(length, breadth):
return length * breadth
area = calculate_area(10, 5)
print("Area of rectangle:", area)
Output: Area of rectangle: 50
Q2 (MCQ): What will the following code print?
python
def add(a, b=10):
return a + b
print(add(5))
print(add(5, 20))
a) 15 and 25 b) 5 and 25 c) 15 and 15 d) Error
Answer: a) 15 and 25 — add(5) uses the default b=10, giving 5+10=15. add(5, 20) overrides the default with 20, giving 5+20=25.
Frequently Asked Questions
Q1: Do I need to use return in every function? No. A function without return performs an action (like printing) but gives nothing back. If you try to store its result — x = greet() — Python stores None. Use return when the caller needs the computed value. Skip it when the function’s job is just to do something, not compute something.
Q2: Can I call a function before defining it in Python? No — Python reads code top to bottom. If you call greet() before the def greet(): block, you get a NameError: name 'greet' is not defined. Always define functions before calling them, or put all function definitions at the top of your file.
Q3: What is the difference between print() inside a function and return? print() displays text on screen — nothing is sent back to the caller. return sends a value that the caller can store and use later. Example: result = square(5) works only if square() has a return statement. If it only has print(x**2) instead, result will be None.