Skip to main content

Command Palette

Search for a command to run...

Ultimate Guide for the Functions in Python

Updated
5 min read
Ultimate Guide for the Functions in Python
P
Highly motivated Data Science and AI professional with a strong academic foundation in Physics, Chemistry, and Mathematics (B.Sc.). Completed a Data Science and AI Diploma from the reputed institute DataMites, gaining hands-on experience in machine learning, deep learning, and natural language processing (NLP). Successfully completed an Internship as a Data Science Intern at Rubixe AI Solutions, where I worked on real-world datasets, built predictive and analytical models, and contributed to businessdriven AI solutions. Passionate about applying data-driven techniques to solve complex problems and deliver impactful insights.

Functions in Python: Complete Guide with Types and Examples

Introduction

Functions are one of the most important building blocks in Python. They allow you to write reusable, organized, and modular code. Instead of repeating the same logic multiple times, you can define it once inside a function and use it whenever needed.

In this blog, you’ll learn:

  • What a function is

  • Why functions are important

  • Types of functions in Python

  • Function arguments and return types

  • Advanced function concepts

  • Real-world examples


1. What is a Function in Python?

A function is a block of reusable code that performs a specific task.

Basic Syntax

def function_name(parameters):
    # block of code
    return value

Example: Simple Function

def greet():
    print("Hello, Welcome to Python!")
    
greet()

Output:

Hello, Welcome to Python!

2. Why Functions Are Important

✅ Code reusability
✅ Reduces repetition
✅ Improves readability
✅ Easier debugging
✅ Modular programming


3. Types of Functions in Python

Python mainly has two broad categories:

  1. Built-in Functions

  2. User-defined Functions


3.1 Built-in Functions

These are predefined functions provided by Python.

Examples

print("Hello")
len([1, 2, 3])
sum([10, 20, 30])
type(10)

Common Built-in Functions

Function Purpose
print() Display output
len() Length of object
sum() Sum of values
max() Largest value
min() Smallest value
type() Data type

3.2 User-Defined Functions

Functions created by the user using def.


A. Function Without Parameters

def welcome():
    print("Welcome User")
    
welcome()

B. Function With Parameters

def greet(name):
    print("Hello", name)

greet("Pranav")

C. Function With Return Value

def add(a, b):
    return a + b

result = add(5, 3)
print(result)

4. Types of Function Arguments


4.1 Positional Arguments

Arguments passed in correct order.

def subtract(a, b):
    return a - b

subtract(10, 5)

4.2 Keyword Arguments

Arguments passed using parameter names.

subtract(b=5, a=10)

4.3 Default Arguments

Default value if no argument provided.

def greet(name="Guest"):
    print("Hello", name)

greet()
greet("Pranav")

4.4 Variable-Length Arguments

*args (Non-keyword)

def total(*numbers):
    return sum(numbers)

total(1, 2, 3, 4)

**kwargs (Keyword Arguments)

def display(**info):
    print(info)

display(name="Pranav", age=21)

5. Anonymous Functions (Lambda Functions)

Small one-line functions using lambda.

square = lambda x: x * x
print(square(5))

Used In:

  • Sorting

  • Data processing

  • Pandas operations


6. Recursive Functions

A function that calls itself.

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)

factorial(5)

Used In:

  • Mathematical problems

  • Tree traversal

  • Divide & conquer algorithms


7. Nested Functions

Function inside another function.

def outer():
    def inner():
        print("Inner Function")
    inner()

outer()

8. Higher-Order Functions

Functions that take another function as argument.

def apply(func, value):
    return func(value)

apply(lambda x: x*2, 10)

9. Generator Functions

Use yield instead of return.

def count_up(n):
    for i in range(n):
        yield i

for num in count_up(5):
    print(num)

Advantage:

  • Memory efficient

  • Used in large data processing


10. Decorator Functions

Functions that modify other functions.

def decorator_func(func):
    def wrapper():
        print("Before function")
        func()
        print("After function")
    return wrapper

@decorator_func
def say_hello():
    print("Hello")

say_hello()

11. Function Scope & Lifetime

Local Scope

Variables inside function.

Global Scope

Variables outside function.

x = 10

def show():
    print(x)

show()

12. Real-World Example

Example: Calculate Student Grade

def calculate_grade(marks):
    if marks >= 90:
        return "A"
    elif marks >= 75:
        return "B"
    else:
        return "C"

print(calculate_grade(85))

13. Difference Between Return and Print

Return Print
Sends value back Displays output
Used in calculations Used for output only
Can be stored Cannot be reused

14. Best Practices for Writing Functions

✔ Use meaningful names
✔ Keep functions small
✔ Avoid global variables
✔ Use docstrings
✔ Follow PEP8 naming conventions


15. Summary of Function Types

Type Description
Built-in Predefined functions
User-defined Created by user
Lambda Anonymous functions
Recursive Calls itself
Generator Uses yield
Higher-order Takes function as argument
Decorator Modifies another function

Conclusion

Functions are essential in Python for building scalable, modular, and maintainable programs. From simple built-in functions to advanced decorators and generators, mastering functions improves both your coding efficiency and problem-solving ability.

Whether you are working in web development, data science, machine learning, or automation, functions are fundamental to writing clean and professional Python code.


Final Thought

Master functions deeply — they are the backbone of structured and efficient programming.


Visual diagrams of function flow