Functions in Python
What is a Function?
A function is a reusable block of code that performs a specific task.
Instead of writing the same code again and again, we write it once inside a function and call it whenever we need it.
Real life example:
- You have a washing machine. You put clothes and press a button → it washes.
- You don’t need to understand the internal motor every time.
- You just use it again and again.
In the same way, a function takes some input (optional), does some work, and can give output back.
Advantages of using functions:
- Code reusability (write once, use many times)
- Better organization of code
- Easier to debug and maintain
- Makes large programs manageable
How to Create a Function
We use the keyword def to define a function.
Basic Syntax:
def function_name():
# code block
statement 1
statement 2
Rules for function name:
- Must start with a letter or underscore
- Can contain letters, numbers and underscore
- Cannot use spaces or special symbols
- Should be meaningful (good practice)
Example 1 – Simple function
def greet():
print("Welcome to KSR DATAVIZON")
print("Happy Learning!")
# Function is created but nothing is printed yet
# We have only defined it
How to Call a Function
To use a function, we write its name followed by parentheses ().
def greet():
print("Welcome to KSR DATAVIZON")
print("Happy Learning!")
# Calling the function
greet()
greet()
greet()
Welcome to KSR DATAVIZON
Happy Learning!
Welcome to KSR DATAVIZON
Happy Learning!
Welcome to KSR DATAVIZON
Happy Learning!
We called the same function three times. This is the power of reusability.
Parameters (Inputs to Function)
Parameters are variables that receive values when the function is called. They make the function flexible.
Syntax:
def function_name(parameter1, parameter2):
# use parameter1 and parameter2 inside the function
print(parameter1)
print(parameter2)
Example 1 – Function with one parameter
def greet(name):
print("Hello", name)
print("Welcome to the course")
greet("Kundan")
greet("Priya")
greet("Rahul")
name receives that value.
Example 2 – Function with multiple parameters
def student_info(name, age, course):
print("Name :", name)
print("Age :", age)
print("Course :", course)
print("-" * 20)
student_info("Kundan", 22, "Data Analytics")
student_info("Priya", 21, "Data Science")
The return Statement
So far our functions only printed values. But many times we want the function to give a result back so that we can use it later.
For this we use the return keyword.
def add(a, b):
result = a + b
return result
total = add(15, 25)
print("Total =", total)
print("Double of total =", total * 2)
total and used it again.
Important points about return:
- When Python sees
return, it immediately exits the function - Any code written after
returnin the same block will not run - A function can return only one value (but that value can be a list, tuple, dictionary etc.)
- If you don’t write return, Python returns
Noneby default
Example – Returning multiple values (using tuple)
def min_max(numbers):
minimum = min(numbers)
maximum = max(numbers)
return minimum, maximum # returns a tuple
marks = [78, 92, 65, 88, 71]
low, high = min_max(marks)
print("Lowest marks :", low)
print("Highest marks:", high)
Default Parameter Values
You can give a default value to a parameter. If the caller does not provide a value, the default is used.
def greet(name, message="Welcome to the course"):
print("Hello", name)
print(message)
print("-" * 25)
greet("Kundan")
greet("Priya", "Good morning!")
greet("Rahul")
Rule: Parameters with default values must come after parameters without default values.
Keyword Arguments
When calling a function, you can pass arguments using the parameter names. This is called keyword arguments.
def student_info(name, age, course):
print("Name :", name)
print("Age :", age)
print("Course :", course)
# Positional arguments (order matters)
student_info("Kundan", 22, "Data Analytics")
# Keyword arguments (order does not matter)
student_info(course="Data Science", name="Priya", age=21)
# Mixing both (positional first, then keyword)
student_info("Amit", course="Python", age=23)
Functions with Lists
Lists are very commonly passed to functions.
Example 1 – Calculate average
def calculate_average(numbers):
if len(numbers) == 0:
return 0
total = sum(numbers)
average = total / len(numbers)
return average
marks = [78, 85, 92, 67, 88]
result = calculate_average(marks)
print("Average marks:", result)
Example 2 – Function that modifies a list
def add_item(my_list, item):
my_list.append(item)
print("Item added successfully")
fruits = ["apple", "banana"]
print("Before:", fruits)
add_item(fruits, "mango")
print("After :", fruits)
Example 3 – Filter even numbers
def get_even_numbers(numbers):
even_list = []
for num in numbers:
if num % 2 == 0:
even_list.append(num)
return even_list
data = [10, 15, 22, 33, 40, 51, 60]
print(get_even_numbers(data))
Functions with Tuples
Tuples are often used to return multiple values from a function.
def get_stats(numbers):
total = sum(numbers)
count = len(numbers)
average = total / count
minimum = min(numbers)
maximum = max(numbers)
return total, count, average, minimum, maximum
marks = (78, 85, 92, 67, 88)
t, c, avg, mn, mx = get_stats(marks)
print("Total :", t)
print("Count :", c)
print("Average :", avg)
print("Minimum :", mn)
print("Maximum :", mx)
Example – Accepting a tuple as parameter
def print_point(point):
x, y, z = point
print(f"X = {x}, Y = {y}, Z = {z}")
print_point((10, 20, 30))
print_point((5, 15, 25))
Functions with Sets
def common_skills(set1, set2):
return set1.intersection(set2)
def has_all_required(candidate_skills, required_skills):
return required_skills.issubset(candidate_skills)
my_skills = {"python", "sql", "excel", "powerbi"}
job_required = {"python", "sql", "excel"}
print("Common skills:", common_skills(my_skills, job_required))
print("Has all required?", has_all_required(my_skills, job_required))
Functions with Dictionaries
Passing dictionaries to functions is extremely common in real projects.
def print_student(student):
print("Student Details")
print("-" * 20)
for key, value in student.items():
print(key, ":", value)
print()
def update_marks(student, new_marks):
student["marks"] = new_marks
return student
s1 = {"name": "Kundan", "age": 22, "marks": 85}
print_student(s1)
s1 = update_marks(s1, 92)
print_student(s1)
Example – Calculate grade from dictionary
def get_grade(student):
marks = student.get("marks", 0)
if marks >= 90:
return "A+"
elif marks >= 80:
return "A"
elif marks >= 70:
return "B"
elif marks >= 60:
return "C"
else:
return "F"
students = [
{"name": "Rahul", "marks": 85},
{"name": "Priya", "marks": 92},
{"name": "Amit", "marks": 67}
]
for s in students:
grade = get_grade(s)
print(s["name"], "→ Grade:", grade)
Variable Scope (Local vs Global)
Local Variable: Created inside a function. Exists only inside that function.
Global Variable: Created outside all functions. Can be accessed anywhere.
x = 100 # global variable
def my_function():
y = 50 # local variable
print("Inside function, x =", x)
print("Inside function, y =", y)
my_function()
print("Outside function, x =", x)
# print(y) → this will give error because y is local
Changing global variable inside function
count = 0
def increment():
global count
count = count + 1
print("Count is now:", count)
increment()
increment()
increment()
print("Final count:", count)
global keyword, Python would create a new local variable and the original count would not change.
Lambda (Anonymous) Functions
A lambda function is a small one-line function without a name.
Syntax:
lambda parameters: expression
Normal function vs Lambda
# Normal function
def square(x):
return x * x
print(square(5))
# Same thing using lambda
square = lambda x: x * x
print(square(5))
Lambda with multiple arguments
add = lambda a, b: a + b
print(add(10, 20))
maximum = lambda a, b: a if a > b else b
print(maximum(45, 78))
Most common use – with map(), filter(), sorted()
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# map → apply a function to every item
squares = list(map(lambda x: x ** 2, numbers))
print("Squares:", squares)
# filter → keep only items that satisfy condition
even = list(filter(lambda x: x % 2 == 0, numbers))
print("Even numbers:", even)
# sorted with custom key
students = [("Rahul", 85), ("Priya", 92), ("Amit", 78)]
sorted_students = sorted(students, key=lambda x: x[1], reverse=True)
print("Sorted by marks:", sorted_students)
*args and **kwargs
Sometimes you don’t know how many arguments will be passed to the function.
*args → for variable number of positional arguments (received as a tuple)
def add_all(*numbers):
total = 0
for num in numbers:
total += num
return total
print(add_all(10, 20))
print(add_all(5, 10, 15, 20, 25))
print(add_all(100))
**kwargs → for variable number of keyword arguments (received as a dictionary)
def print_details(**info):
for key, value in info.items():
print(key, ":", value)
print_details(name="Kundan", age=22, course="Data Analytics")
print()
print_details(name="Priya", city="Mumbai", marks=92)
Real-World Examples
Example 1 – Customer filter function
customers = [
{"name": "Amit", "age": 34, "balance": 75000, "job": "management"},
{"name": "Priya", "age": 28, "balance": 32000, "job": "technician"},
{"name": "Rahul", "age": 41, "balance": 95000, "job": "management"},
{"name": "Sneha", "age": 25, "balance": 18000, "job": "admin"}
]
def filter_customers(data, min_balance=50000, job_type=None):
result = []
for cust in data:
if cust["balance"] >= min_balance:
if job_type is None or cust["job"] == job_type:
result.append(cust)
return result
print("High balance customers:")
for c in filter_customers(customers):
print(c["name"], "→", c["balance"])
print("\nManagement with high balance:")
for c in filter_customers(customers, job_type="management"):
print(c["name"], "→", c["balance"])
Example 2 – Simple calculator using functions
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Cannot divide by zero"
return a / b
print(add(20, 10))
print(subtract(20, 10))
print(multiply(20, 10))
print(divide(20, 10))
print(divide(20, 0))
Functions in Python
Complete and detailed explanation of functions, parameters, return, lambda and more.
Select any topic from the left sidebar to begin.
Start Learning →
