The def keyword in Python is used to define a function. Functions are logical blocks of code that can be reused multiple times. For example:
def func():
print("Hello")
func()
Output
Hello
Explanation:
- def func(): Defines a function named func.
- print("Hello"): Code inside the function that runs when called.
- func(): Calls the function, printing Hello to the output.
The below diagram shows the basic structure of a Python function, including its name, parameters, body, and optional return value.

Syntax
def function_name(parameters):
# Code to execute
return value # Optional
- def: Keyword to define a function
- function_name: Name of the function
- parameters: Optional input values (can be empty)
- return: Optional, sends a value back from the function
- The indented block is executed when the function is called
Examples
Example 1: In this example, we create a function sub() using the def keyword, which calculates the difference between two numbers.
def sub(x, y):
return (x-y)
a = 90
b = 50
res = sub(a, b)
print("subtraction of ", a, " and ", b, " is ", res)
Output
subtraction of 90 and 50 is 40
Explanation:
- def sub(x, y): Defines a function named sub that takes two parameters x and y.
- return (x-y): Returns the difference between x and y.
- res = sub(a, b): Calls the function with a and b, storing the result in res.
Example 2: In this example, we define a user-defined function fun() using the def keyword. The function takes a parameter n and prints the first n prime numbers.
def fun(n):
x = 2
count = 0
while count < n:
for d in range(2, int(x ** 0.5) + 1):
if x % d == 0:
break
else:
print(x)
count += 1
x += 1
n = 10
fun(n)
Output
2 3 5 7 11 13 17 19 23 29
Explanation:
- fun(n): Prints the first n prime numbers.
- x = 2, count = 0: Initialize number and prime counter.
- while count < n: Loop until n primes are found.
- for d in range(2, int(x**0.5)+1): Check if x is divisible by any number up to √x.
- if x % d == 0: break: Not prime, skip.
- else: If prime, print x and increment count.
- x += 1: Check next number.
Passing Function as an Argument
In Python, functions are first-class objects, which means you can pass functions as arguments to other functions, allowing you to call it inside that function.
def fun(func, arg):
return func(arg)
def square(x):
return x ** 2
res = fun(square, 5)
print(res)
Output
25
Explanation:
- def fun(func, arg): Defines a function that takes another function func and an argument arg.
- return func(arg): Calls the passed function with the given argument and returns the result.
- def square(x): Defines a function that returns the square of x.
- res = fun(square, 5): Passes the square function and 5 to fun.
Using *args
*args allows a function to accept a variable number of positional arguments, which are collected into a tuple, making the function flexible to handle multiple inputs.
def fun(*args):
for arg in args:
print(arg)
fun(1, 2, 3, 4, 5)
Output
1 2 3 4 5
Explanation:
- def fun(*args): Defines a function that can take any number of positional arguments, stored as a tuple args.
- fun(1, 2, 3, 4, 5): Calls the function with 5 positional arguments.
Using **kwargs
**kwargs lets a function accept any number of keyword arguments. These arguments are collected into a dictionary, with keys as argument names and values as their corresponding values.
def fun(**kwargs):
for k, val in kwargs.items():
print(f"{k}: {val}")
fun(name="Olivia", age=30, city="New York")
Output
name: Olivia age: 30 city: New York
Explanation:
- def fun(**kwargs): Defines a function that can take any number of keyword arguments, stored as a dictionary kwargs.
- fun(name="Leo", age=30, city="New York"): Calls the function with 3 keyword arguments.
Using def Inside a Class
Inside a class, functions are called methods. You define them using def just like regular functions, but they usually take self as the first parameter to access the object’s attributes and other methods.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Name - {self.name} and Age - {self.age}.")
p1 = Person("Harry", 30)
p1.greet()
Output
Name - Harry and Age - 30.
Explanation:
- def __init__(self, name, age): Constructor method called when a new object is created.
- self.name = name and self.age = age: Initialize object attributes.
- def greet(self): Defines a method greet that can access the object’s attributes.
- p1.greet(): Calls the greet method on p1, outputting:
