Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: Types of Functions

Python Types of Functions - Built-in vs User-defined

Learn about the different types of functions available in Python.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Introduction to Function Types
  • Built-in Functions
  • User-Defined Functions
  • Lambda Functions
  • Recursive Functions
  • Higher-Order Functions
  • Comparison of Function Types
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • Built-in functions — Python's ready-to-use functions
  • User-defined functions — creating your own functions
  • Lambda functions — anonymous one-liner functions
  • Recursive functions — functions that call themselves
  • Higher-order functions — functions that operate on other functions
  • When to use each type — choosing the right function type

Introduction to Function Types

Python provides several types of functions, each serving different purposes. Understanding the different types helps you choose the right tool for the job and write more efficient, readable code.

šŸ’” Key concept: Python functions can be classified into multiple categories based on how they are defined, where they come from, and how they behave. The main types are built-in, user-defined, lambda, recursive, and higher-order functions.

Built-in Functions

1

Python's Ready-to-Use Functions

# Python comes with many built-in functions ready to use
# No need to import them — they're always available

# 1. Type Conversion Functions
print(int("123"))           # 123 — convert string to integer
print(float("45.67"))       # 45.67 — convert to float
print(str(100))             # "100" — convert to string
print(list("abc"))          # ['a', 'b', 'c'] — convert to list
print(tuple([1, 2, 3]))     # (1, 2, 3) — convert to tuple
print(dict([("a", 1), ("b", 2)]))  # {'a': 1, 'b': 2}

# 2. Math Functions
print(abs(-10))             # 10 — absolute value
print(max(5, 10, 3))        # 10 — maximum value
print(min(5, 10, 3))        # 3 — minimum value
print(sum([1, 2, 3, 4]))    # 10 — sum of elements
print(pow(2, 3))            # 8 — 2 raised to power 3
print(round(3.14159, 2))    # 3.14 — round to 2 decimal places

# 3. Sequence Functions
numbers = [3, 1, 4, 1, 5]
print(len(numbers))         # 5 — length of sequence
print(sorted(numbers))      # [1, 1, 3, 4, 5] — sorted list
print(sum(numbers))         # 14 — sum of elements
print(min(numbers))         # 1 — minimum value
print(max(numbers))         # 5 — maximum value

# 4. Input/Output Functions
# print() — display output
# input() — get user input

# 5. Type Checking Functions
print(type(10))             # 
print(isinstance(10, int))  # True
print(isinstance("hello", str))  # True

# 6. Other Useful Built-ins
print(all([True, True, False]))  # False — all elements True?
print(any([True, False, False])) # True — any element True?
print(enumerate(["a", "b", "c"])) # enumerate object
print(zip([1, 2], ["a", "b"]))    # zip object

Categories of built-in functions:

  • Type Conversion — int(), str(), list(), tuple()
  • Mathematical — abs(), max(), min(), sum(), round()
  • Sequence Operations — len(), sorted(), reversed()
  • Type Checking — type(), isinstance()
  • Input/Output — print(), input()
  • Iteration Helpers — enumerate(), zip(), map()

Quick Check: What is a built-in function? (Answer: A function that comes with Python and is always available without importing)

User-Defined Functions

2

Creating Your Own Functions

# User-defined functions are created using the 'def' keyword

# 1. Simple function — no parameters, no return
def greet():
    """Print a greeting"""
    print("Hello, World!")

greet()  # Hello, World!

# 2. Function with parameters
def greet_person(name):
    """Greet a specific person"""
    print(f"Hello, {name}!")

greet_person("Alice")  # Hello, Alice!

# 3. Function with return value
def add(a, b):
    """Add two numbers and return the result"""
    return a + b

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

# 4. Function with default parameters
def greet_user(name="Guest"):
    """Greet a user with a default name"""
    return f"Welcome, {name}!"

print(greet_user())       # Welcome, Guest!
print(greet_user("Bob"))  # Welcome, Bob!

# 5. Function with multiple return values
def get_user_info():
    """Return multiple values as a tuple"""
    return "Alice", 25, "Engineer"

name, age, job = get_user_info()
print(f"{name} is {age} and works as {job}")

# 6. Function with variable arguments (*args)
def sum_all(*args):
    """Sum any number of arguments"""
    return sum(args)

print(sum_all(1, 2, 3, 4, 5))  # 15

# 7. Function with keyword arguments (**kwargs)
def print_info(**kwargs):
    """Print key-value pairs"""
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="NYC")

User-defined function features:

  • Created with def keyword
  • Can have parameters (inputs)
  • Can have return values (outputs)
  • Can have default parameters
  • Can accept variable arguments (*args, **kwargs)
  • Can have docstrings for documentation

Quick Check: What keyword is used to create a user-defined function? (Answer: def)

Lambda Functions (Anonymous Functions)

3

One-Liner Anonymous Functions

# Lambda functions are small, anonymous functions
# Syntax: lambda arguments: expression

# 1. Simple lambda function
square = lambda x: x ** 2
print(square(5))  # 25

# 2. Lambda with multiple arguments
add = lambda a, b: a + b
print(add(3, 4))  # 7

# 3. Lambda with conditional expression
is_even = lambda x: "Even" if x % 2 == 0 else "Odd"
print(is_even(4))  # Even
print(is_even(7))  # Odd

# 4. Lambda with map() — apply to all elements
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # [1, 4, 9, 16, 25]

# 5. Lambda with filter() — filter elements
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4, 6, 8, 10]

# 6. Lambda with sorted() — custom sorting
people = [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 25},
    {"name": "Charlie", "age": 35}
]
sorted_by_age = sorted(people, key=lambda x: x["age"])
print(sorted_by_age)  # Sorted by age

# 7. Lambda with reduce()
from functools import reduce
product = reduce(lambda x, y: x * y, [1, 2, 3, 4])
print(product)  # 24

Lambda function characteristics:

  • Anonymous — no function name
  • Single expression — can only have one line
  • Returns automatically — the expression is returned
  • Best for simple operations — not for complex logic
  • Common with map(), filter(), sorted() — functional programming

Quick Check: What is a lambda function? (Answer: An anonymous, single-expression function defined with the lambda keyword)

Recursive Functions

4

Functions That Call Themselves

# A recursive function calls itself to solve a problem
# Must have a base case to stop recursion

# 1. Factorial using recursion
def factorial(n):
    """Calculate n! using recursion"""
    # Base case
    if n <= 1:
        return 1
    # Recursive case
    return n * factorial(n - 1)

print(factorial(5))  # 120 (5*4*3*2*1)

# 2. Fibonacci sequence
def fibonacci(n):
    """Calculate the nth Fibonacci number"""
    # Base cases
    if n <= 0:
        return 0
    if n == 1:
        return 1
    # Recursive case
    return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(7))  # 13
print(fibonacci(10)) # 55

# 3. Sum of numbers from 1 to n
def sum_to_n(n):
    """Sum numbers from 1 to n"""
    if n <= 0:
        return 0
    return n + sum_to_n(n - 1)

print(sum_to_n(10))  # 55

# 4. Power calculation
def power(base, exponent):
    """Calculate base^exponent recursively"""
    if exponent == 0:
        return 1
    if exponent == 1:
        return base
    return base * power(base, exponent - 1)

print(power(2, 5))   # 32
print(power(3, 4))   # 81

# 5. List sum recursively
def recursive_sum(numbers):
    """Sum elements of a list recursively"""
    if not numbers:
        return 0
    return numbers[0] + recursive_sum(numbers[1:])

print(recursive_sum([1, 2, 3, 4, 5]))  # 15

# Important: Recursion has a depth limit
import sys
print(sys.getrecursionlimit())  # Default is 1000

Recursive function components:

  • Base case — condition to stop recursion
  • Recursive case — function calls itself
  • Progress toward base case — each call gets closer
  • Depth limit — Python limits recursion depth to 1000
  • Best for tree-like structures — directories, file systems

Quick Check: What is a recursive function? (Answer: A function that calls itself with a base case to stop)

Higher-Order Functions

5

Functions That Work With Other Functions

# Higher-order functions either:
# 1. Take other functions as arguments
# 2. Return functions as results

# 1. Function as argument
def apply_operation(operation, a, b):
    """Apply any operation to two numbers"""
    return operation(a, b)

def add(x, y):
    return x + y

def multiply(x, y):
    return x * y

print(apply_operation(add, 5, 3))       # 8
print(apply_operation(multiply, 5, 3))  # 15

# 2. Using lambda with higher-order functions
print(apply_operation(lambda x, y: x - y, 10, 3))  # 7

# 3. Function returning a function
def create_multiplier(factor):
    """Create a function that multiplies by a factor"""
    def multiplier(x):
        return x * factor
    return multiplier

double = create_multiplier(2)
triple = create_multiplier(3)

print(double(5))   # 10
print(triple(5))   # 15

# 4. Decorators — a common higher-order function pattern
def timer(func):
    """Decorator to measure execution time"""
    import time
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start:.6f} seconds")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(0.1)
    return "Done"

slow_function()  # slow_function took 0.100001 seconds

# 5. Built-in higher-order functions
# map(), filter(), reduce(), sorted() with key

# map() — apply function to all elements
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # [1, 4, 9, 16, 25]

# filter() — filter elements
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4]

Higher-order function concepts:

  • Functions as arguments — pass functions to other functions
  • Functions as return values — return functions from functions
  • Decorators — modify behavior of functions
  • Functional programming tools — map(), filter(), reduce()
  • Closures — functions that remember their environment

Quick Check: What is a higher-order function? (Answer: A function that takes other functions as arguments or returns functions)

Comparison of Function Types

6

When to Use Each Type

# Summary of function types

print("=" * 60)
print("FUNCTION TYPES COMPARISON")
print("=" * 60)

# 1. Built-in Functions
print("\nšŸ“Œ BUILT-IN FUNCTIONS")
print("  - Examples: print(), len(), type(), sum(), max()")
print("  - When to use: Common operations that Python provides")
print("  - Advantages: Fast, optimized, always available")
print("  - Limitations: Limited to what Python provides")

# 2. User-Defined Functions
print("\nšŸ“Œ USER-DEFINED FUNCTIONS")
print("  - Examples: def calculate_area(), def greet_user()")
print("  - When to use: Custom logic, reusable code")
print("  - Advantages: Flexible, readable, reusable")
print("  - Limitations: Need to write and maintain them")

# 3. Lambda Functions
print("\nšŸ“Œ LAMBDA FUNCTIONS")
print("  - Examples: lambda x: x*2, lambda a,b: a+b")
print("  - When to use: Simple one-time operations")
print("  - Advantages: Concise, no function definition needed")
print("  - Limitations: Single expression only, less readable")

# 4. Recursive Functions
print("\nšŸ“Œ RECURSIVE FUNCTIONS")
print("  - Examples: factorial(), fibonacci(), tree traversal")
print("  - When to use: Problems that have recursive structure")
print("  - Advantages: Elegant for certain problems")
print("  - Limitations: Depth limit, memory intensive")

# 5. Higher-Order Functions
print("\nšŸ“Œ HIGHER-ORDER FUNCTIONS")
print("  - Examples: map(), filter(), decorators")
print("  - When to use: Functional programming, decorators")
print("  - Advantages: Powerful abstraction, reusable patterns")
print("  - Limitations: Can be complex, harder to debug")

Choosing the right function type:

  • Built-in — use when Python already provides it
  • User-defined — use for custom, reusable logic
  • Lambda — use for simple, one-time operations
  • Recursive — use for problems with recursive structure
  • Higher-order — use for functional programming patterns

Quick Check: When should you use a lambda function? (Answer: For simple, one-line operations where a full function definition isn't needed)

Try It Yourself

Experiment with different types of functions in the editor below.

Loading Pyodide... 0%
Python Code Editor
========================================
TYPES OF FUNCTIONS PRACTICE
========================================

1. BUILT-IN FUNCTIONS
Numbers: [3, 1, 4, 1, 5, 9, 2, 6]
Length: 8
Sum: 31
Max: 9
Min: 1
Sorted: [1, 1, 2, 3, 4, 5, 6, 9]

2. USER-DEFINED FUNCTION
Hello, Alice!
5 + 3 = 8

3. LAMBDA FUNCTION
Square of 7: 49
Squared: [1, 4, 9, 16, 25]

4. RECURSIVE FUNCTION
Factorial of 5: 120
Factorial of 7: 5040

5. HIGHER-ORDER FUNCTION
5 * 4 = 20
10 + 5 = 15

Types of functions practice complete!
šŸ†

You've Got It!

You now understand the different types of functions in Python — built-in, user-defined, lambda, recursive, and higher-order functions. You know when and how to use each type.

Quick Quiz

Test what you've learned:

1. Which of the following is a built-in function in Python?
2. What is a lambda function?
3. What is a recursive function?
4. What is a higher-order function?
5. Which type of function is best for simple one-time operations?

Frequently Asked Questions

What is the difference between built-in and user-defined functions? ā–¼

Built-in functions come with Python and are always available (e.g., print(), len()). User-defined functions are created by programmers using the def keyword for specific needs.

When should I use a lambda function instead of a regular function? ā–¼

Use lambda functions for simple, one-line operations where a full function definition would be overkill. They're commonly used with map(), filter(), and sorted() for concise code.

What is the recursion limit in Python? ā–¼

Python has a default recursion limit of 1000. You can check it with sys.getrecursionlimit() and modify it with sys.setrecursionlimit(), but be careful as deep recursion can cause stack overflow.

What is a decorator in Python? ā–¼

A decorator is a higher-order function that takes another function as input, adds some functionality, and returns a new function. It's a powerful way to modify or enhance function behavior without changing the function itself.

What's a common interview question about function types? ā–¼

Common questions include: "Explain the difference between built-in and user-defined functions," "What is a lambda function and when would you use it?" and "Explain recursion with an example."

Can a function be both recursive and anonymous? ā–¼

Yes, though it's tricky. You can create a recursive lambda function by assigning it to a name and referencing itself, or by using the Y combinator pattern. However, it's generally better to use a regular function for recursion for readability.

Where to Go From Here

Now that you understand the different types of functions, check out these related topics:

Inbuilt Functions

Explore Python's most useful built-in functions in detail.

Learn More →

User-Defined Functions

Learn why and how to create your own functions.

Learn More →

Function Arguments

Master different types of function arguments.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
Previous: Modular Programming Next: Inbuilt Functions →