User define Function in python are one of the most important building blocks of Python programming. They help you organize your code, reuse logic, and make programs easier to read and maintain. In this guide, we’ll explore what functions are, why they’re useful, how to create them, and different types of functions with practical examples.

in previous tutorial we have learned the Input and Output Operations in Python we you not visited then click here
What are Functions in Python?
A user define function is a block of reusable code that performs a specific task. Instead of writing the same code multiple times, you can define it once inside a function and call it whenever needed.
Think of a function as a machine:
Input → Materials you give to the machine (called parameters).
Process → The machine works on those materials (code inside the function).
Output → The final product returned by the machine (called return value).
Why Use Functions?
Here are some benefits of using user defined functions in Python:
✅ Code Reusability: Write once, use multiple times.
✅ Better Organization: Break down large programs into smaller, manageable chunks.
✅ Avoid Repetition: No need to copy the same logic everywhere.
✅ Improved Debugging: Easier to find and fix bugs.
✅ Collaboration: Multiple developers can work on different functions at the same time.
How to Define a Function in Python
user define function in python uses def keyword to define a function.
Syntax:
def function_name(parameters):
“””Optional: Function description (docstring)”””
# Code block
return value
Example: A Simple Function
def greet():
print(“Hello, Welcome to Python Functions!”)
calling the function
greet()
Output:
Hello, Welcome to Python Functions!
A)Function with Parameters
Parameters allow you to pass information into a function.
def greet_user(name):
print(f”Hello, {name}! Welcome to Python.”)
greet_user(“John”)
OUTPUT:
Hello, John! Welcome to Python.
Return Statement in Functions
The return keyword sends a result back to the caller.
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(“Sum is:”, result)
Output:
Sum is: 8
Tip: If you don’t use return, the function will return None by default.
_________________________________________________
The Types of Function Arguments in Python
python follow the below user define function in python. Define Function in Python with Example are as below
Python supports four types of function arguments:
Type | Example |
---|---|
Positional Arguments | Order matters |
Keyword Arguments | Arguments are matched by name |
Default Arguments | Assign default values |
Variable-Length Arguments | *args and **kwargs |
_________________________________________________
1) Positional Arguments
The order of values must match the order of parameters.
def student_info(name, age):
print(f”Name: {name}, Age: {age}”)
student_info(“John”, 21)
output:
Name: John, Age: 21
2) Keyword Arguments
Pass arguments using parameter names, so order doesn’t matter.
student_info(age=21, name=”John”)
3) Default Arguments
Provide default values to parameters.
def greet(name=”Guest”):
print(f”Hello, {name}!”)
greet() # Uses default value
greet(“Jhon”) # Overrides default
Output:
Hello, Guest!
Hello, Jhon!
4) Variable-Length Arguments
Using *args (Non-Keyword)
Collects multiple values into a tuple
def add_all(*numbers):
total = sum(numbers)
print(“Total:”, total)
add_all(2, 4, 6, 8)
output:
Total: 20
5) Using **kwargs (Keyword)
Collects multiple key-value pairs into a dictionary.
def display_info(**details):
for key, value in details.items():
print(f”{key}: {value}”)
display_info(Name=”John”, Age=21, City=”Pune”)
output:
Name: John
Age: 21
City: Pune
Lambda Functions (Anonymous Functions)
A lambda function is a one-line function without a name.
Perfect for short, temporary tasks.
Example:
square = lambda x: x * x
print(square(5))
Output
25
Nested Functions
You can define one function inside another.
def outer():
def inner():
print(“I am inside the inner function.”)
inner()
outer()
OUTPUT:
I am inside the inner function.
Built-in Functions in Python
Python provides many built-in functions like:
print()
len()
max(), min()
sorted()
sum()
type()
These are ready-to-use and do not require defining manually.
Best Practices for Writing Functions
Use meaningful names for functions and parameters.
Keep functions small and focused on one task.
Add docstrings to explain what your function does.
Avoid global variables inside functions.
Use type hints for clarity (Python 3.6+).
def add(a: int, b: int) -> int:
“””This function returns the sum of two numbers.”””
return a + b
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):
return a / b
print(“Select operation: +, -, *, /”)
op = input(“Enter operator: “)
x = int(input(“Enter first number: “))
y = int(input(“Enter second number: “))
if op == ‘+’:
print(“Result:”, add(x, y))
elif op == ‘-‘:
print(“Result:”, subtract(x, y))
elif op == ‘*’:
print(“Result:”, multiply(x, y))
elif op == ‘/’:
print(“Result:”, divide(x, y))
else:
print(“Invalid operator!”)
_________________________________________________
Concept | Key Point |
---|---|
Functions | Block of reusable code |
Parameters | Data passed into functions |
Return Statement | Sends output back |
*args | Accept multiple positional arguments |
**kwargs | Accept multiple keyword arguments |
Lambda | One-line anonymous function |
Summary
So we learned the user define function in python , Functions are the foundation of Python programming.
By mastering them, you’ll write cleaner, reusable, and more efficient code—a crucial step before learning data structures or object-oriented programming
Leave a Reply