Python Foundation

Functions in Python

01 · Introduction Functions · 1 of 15

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
02 · Creating a Function Functions · 2 of 15

How to Create a Function

We use the keyword def to define a function.

Basic Syntax:

Python
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

Python
def greet():
    print("Welcome to KSR DATAVIZON")
    print("Happy Learning!")

# Function is created but nothing is printed yet
# We have only defined it
Defining a function does not run the code inside it. The code runs only when we call the function.
03 · Calling a Function Functions · 3 of 15

How to Call a Function

To use a function, we write its name followed by parentheses ().

Python
def greet():
    print("Welcome to KSR DATAVIZON")
    print("Happy Learning!")

# Calling the function
greet()
greet()
greet()
Output:
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.
04 · Parameters Functions · 4 of 15

Parameters (Inputs to Function)

Parameters are variables that receive values when the function is called. They make the function flexible.

Syntax:

Python
def function_name(parameter1, parameter2):
    # use parameter1 and parameter2 inside the function
    print(parameter1)
    print(parameter2)

Example 1 – Function with one parameter

Python
def greet(name):
    print("Hello", name)
    print("Welcome to the course")

greet("Kundan")
greet("Priya")
greet("Rahul")
Each time we call the function, we pass a different name. The parameter name receives that value.

Example 2 – Function with multiple parameters

Python
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")
05 · Return Statement Functions · 5 of 15

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.

Python
def add(a, b):
    result = a + b
    return result

total = add(15, 25)
print("Total =", total)

print("Double of total =", total * 2)
The function calculated 15 + 25 = 40 and returned it. We stored the returned value in the variable total and used it again.

Important points about return:

  • When Python sees return, it immediately exits the function
  • Any code written after return in 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 None by default

Example – Returning multiple values (using tuple)

Python
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)
06 · Default Parameters Functions · 6 of 15

Default Parameter Values

You can give a default value to a parameter. If the caller does not provide a value, the default is used.

Python
def greet(name, message="Welcome to the course"):
    print("Hello", name)
    print(message)
    print("-" * 25)

greet("Kundan")
greet("Priya", "Good morning!")
greet("Rahul")
In the first and third call we did not pass the second argument, so the default message was used. In the second call we over-rode the default message.

Rule: Parameters with default values must come after parameters without default values.

07 · Keyword Arguments Functions · 7 of 15

Keyword Arguments

When calling a function, you can pass arguments using the parameter names. This is called keyword arguments.

Python
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)
08 · With Lists Functions · 8 of 15

Functions with Lists

Lists are very commonly passed to functions.

Example 1 – Calculate average

Python
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

Python
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)
Lists are mutable. When you pass a list to a function and modify it inside, the original list also changes.

Example 3 – Filter even numbers

Python
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))
09 · With Tuples Functions · 9 of 15

Functions with Tuples

Tuples are often used to return multiple values from a function.

Python
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

Python
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))
10 · With Sets Functions · 10 of 15

Functions with Sets

Python
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))
11 · With Dictionaries Functions · 11 of 15

Functions with Dictionaries

Passing dictionaries to functions is extremely common in real projects.

Python
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

Python
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)
12 · Variable Scope Functions · 12 of 15

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.

Python
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

Python
count = 0

def increment():
    global count
    count = count + 1
    print("Count is now:", count)

increment()
increment()
increment()
print("Final count:", count)
Without the global keyword, Python would create a new local variable and the original count would not change.
13 · Lambda Functions Functions · 13 of 15

Lambda (Anonymous) Functions

A lambda function is a small one-line function without a name.

Syntax:

Python
lambda parameters: expression

Normal function vs Lambda

Python
# 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

Python
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()

Python
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)
Lambda is best when you need a small function for a short time, especially as an argument to other functions like map, filter or sorted.
14 · *args & **kwargs Functions · 14 of 15

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

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

Python
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)
15 · Real Examples Functions · 15 of 15

Real-World Examples

Example 1 – Customer filter function

Python
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

Python
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))
Home Functions in Python

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 →