Functions in Python: Types, Syntax and Examples

Python has four types of functions: built-in functions (like print() and len()), user-defined functions (written with def), lambda functions (anonymous, single-expression functions), and recursive functions (functions that call themselves). Each type serves a distinct purpose, and choosing the right one is essential for writing clean, reusable Python code.

  • Key Takeaway 1: Python functions are defined with the def keyword, followed by a name, parentheses and a colon.
  • Key Takeaway 2: The four types of functions in Python are built-in, user-defined, lambda and recursive.
  • Key Takeaway 3: *args lets a function accept any number of positional arguments; **kwargs accepts any number of keyword arguments.
  • Key Takeaway 4: Lambda functions are ideal for short, throwaway operations, not for complex logic.
  • Key Takeaway 5: Python consistently ranks in the top three languages on the TIOBE Index, making function fundamentals a high-value skill for any developer.

What a Function Is

A function is a named, reusable block of code that performs a specific task. You define it once, then call it as many times as you need, passing in different data each time. That is the whole point: stop repeating yourself.

In Python, functions are first-class objects. That means you can pass them as arguments, return them from other functions, and assign them to variables. This flexibility is why Python is so popular for everything from scripting to machine learning. According to the Stack Overflow Developer Survey 2024, Python is the most popular programming language overall for the third year running, which makes it the most common first language for students in BTech, BCA and BSc CS programmes across India. NASSCOM reports that Python skills are among the top five most requested competencies in Indian IT hiring, reflecting how central the language has become to the country’s technology workforce.

Before you write your first function, make sure you can actually run Python on your machine. If you have not set that up yet, the guide on how to write and run a Python program at 3.0 University walks you through it step by step.

Basic Function Syntax

The syntax is minimal. You use def, give the function a name, list any parameters in parentheses, add a colon, then indent the body. The return statement sends a value back to the caller. If you omit return, Python returns None by default.

Syntax Element What It Does Required?
def Declares the start of a function definition Yes
Function name Identifies the function; use lowercase with underscores Yes
Parameters Variables the function receives as input No
: Ends the function header, starts the body block Yes
return Sends a value back to the caller No
Docstring Optional string literal describing what the function does No (but recommended)

A practical tip from real code review sessions: always write a one-line docstring, even for small functions. When you come back to your code three weeks later, or when a teammate reads it, that single sentence saves everyone time.

Types of Functions in Python

The different types of functions in Python each solve a different problem. Knowing which type to reach for is a skill you build with practice. Here is a clear breakdown of all four types of functions in Python, with examples for each.

Built-in Functions

Python ships with 68 built-in functions as of Python 3.12, according to the official Python documentation. These include print(), len(), range(), type(), int(), str() and sorted(). You do not import anything to use them; they are always available.

Most beginners use built-in functions from day one without realising they are calling functions at all. When you write len("hello") and get back 5, that is a built-in function doing its job.

User-Defined Functions

A user-defined function in Python is one you write yourself using the def keyword. It is the core of every Python program beyond the basics. A user-defined function wraps a specific piece of logic so you can call it repeatedly without duplicating code.

Here is a simple example. Suppose you are building a fee-calculator for a college portal. Instead of repeating the calculation logic every time, you write it once:

def calculate_fee(base_fee, scholarship_percent):
    discount = base_fee * (scholarship_percent / 100)
    return base_fee - discount

Call it as calculate_fee(80000, 25) and you get 60000.0 back. Clean, readable, reusable. This pattern is common in student projects at institutions like IIT, BITS Pilani and Anna University, where Python is taught as the primary programming language in first-year CS courses.

Lambda Functions

A lambda function is an anonymous function defined in a single line using the lambda keyword. It can take any number of arguments but contains only one expression. The result of that expression is automatically returned.

Syntax: lambda arguments: expression

Lambda function Python example: square = lambda x: x ** 2. Calling square(9) returns 81. Lambda functions shine when you need a quick function inside map(), filter() or sorted(). Do not use them for anything complex; they become unreadable fast, and unreadable code is a bug waiting to happen.

Recursive Functions

A recursive function in Python calls itself until it hits a base case. The classic textbook example is factorial: factorial(5) calls factorial(4), which calls factorial(3), and so on until it reaches factorial(1) and returns 1.

Recursion is elegant for problems like tree traversal and divide-and-conquer algorithms. The risk is a stack overflow if you forget the base case. Python’s default recursion limit is 1,000 calls, which you can check with import sys; sys.getrecursionlimit(). In production code, experienced developers often prefer iteration over recursion for performance reasons, but you will see recursion frequently in coding interviews and data structure problems at companies like TCS, Infosys and Wipro.

Arguments and Return Values

Arguments are how you pass data into a function. Python gives you several ways to handle them, and each has its place.

Positional and Keyword Arguments

Positional arguments match by order. Keyword arguments match by name, so order does not matter. You can mix them, but positional arguments must always come before keyword arguments in the call.

Example: def greet(name, message="Hello"):. Calling greet("Priya") uses the default. Calling greet("Priya", message="Namaste") overrides it. Default parameter values are set at function definition time, not at call time. This trips up beginners when the default value is a mutable object like a list.

*args and **kwargs

*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. Both are used when you do not know in advance how many arguments a caller will pass.

Real-world use: if you are writing a logging utility for a web scraping project, you might want it to accept any number of key-value pairs without changing the function signature every time. That is exactly what **kwargs is for. For more on how Python handles real-world tasks like this, check out the 3.0 University guide on Python for automation, web scraping and APIs.

Scope: Local vs Global

Variables defined inside a function are local; they do not exist outside it. Variables defined at the module level are global. If you need to modify a global variable from inside a function, you declare it with the global keyword. In practice, overusing global variables is a code smell. Functions should receive what they need as arguments and return results cleanly.

Return Values

A function can return a single value, multiple values as a tuple, or nothing at all. Returning multiple values looks like this: return min_val, max_val. The caller unpacks them: low, high = get_range(data). This pattern is common in data science workflows with Pandas and NumPy, where functions often return both a result and metadata.

Python Function Examples

Theory sticks better when you see it applied. Here are three short, practical python function examples that cover the different types of functions in Python.

Example 1: User-Defined Function for Grade Classification

This is the kind of user-defined function in Python a BTech student might write for a marks-processing script:

def classify_grade(marks):
    if marks >= 90:
        return "O"
    elif marks >= 75:
        return "A+"
    elif marks >= 60:
        return "A"
    else:
        return "B"

Call it with classify_grade(82) and it returns "A+". Straightforward, testable, easy to extend.

Example 2: Lambda Function Python Example with sorted()

Sorting a list of student dictionaries by marks in one line:

students = [{"name": "Arjun", "marks": 88}, {"name": "Neha", "marks": 95}]
ranked = sorted(students, key=lambda s: s["marks"], reverse=True)

The lambda here is the right tool. It is short, it lives inline, and it would be overkill to write a full named function for it.

Example 3: Recursive Function in Python for Fibonacci

def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

Clean and readable, but not efficient for large n because it recalculates the same values repeatedly. In an interview, always mention this and suggest memoization as the fix. It shows you understand performance, not just syntax. This kind of thinking is exactly what separates good candidates at technical interviews for software roles at Indian product and service companies alike.

The types of functions in Python are foundational to every advanced topic, whether that is building AI models, writing secure scripts or processing data. The 3.0 University course catalogue covers how to become an AI engineer, and strong function skills are assumed knowledge from day one in those programmes.

Students in BSc Computer Science programmes typically encounter functions in their first-year programming courses, but the depth of understanding covered here, including scope, *args, **kwargs and recursion, often appears only in second-year or placement-prep modules. Getting ahead of that curve now pays off.

If you are exploring which software development tools to learn first, Python is consistently recommended alongside Git and a good IDE, and understanding the types of functions in Python is the first real building block after variables and loops.

Frequently Asked Questions About Types of Functions in Python

What are the types of functions in Python?

Python has four types of functions: built-in functions (pre-loaded with Python, like print() and len()), user-defined functions (created with def), lambda functions (anonymous, single-expression functions), and recursive functions (functions that call themselves with a base case). Each type of function in Python solves a different category of problem, and you will use all four regularly as you progress.

How do I define a function in Python?

Use the def keyword, followed by the function name, parentheses containing any parameters, and a colon. The function body is indented below. Use return to send a value back. For example: def add(a, b): return a + b. Call it with add(3, 4) and you get 7.

What is a lambda function in Python?

A lambda function is a small, anonymous function defined with the lambda keyword in a single line. It takes any number of arguments but evaluates only one expression. Use it for short operations inside map(), filter() or sorted(). For anything more than one line of logic, write a proper named function instead.

What are *args and **kwargs in Python?

*args lets a function accept any number of positional arguments, which are collected into a tuple inside the function. **kwargs lets it accept any number of keyword arguments, collected into a dictionary. Both are useful when you want a flexible function signature that does not break when callers pass different numbers of arguments.

Can you give examples of functions in Python?

Yes. A user-defined function: def square(n): return n ** 2. A lambda function Python example: double = lambda x: x * 2. A recursive function in Python: def factorial(n): return 1 if n == 1 else n * factorial(n - 1). Each example shows a different type of function in Python in action, and all three are common in Python programs at every level from student projects to production code.

You now have a complete, working understanding of the types of functions in Python: what they are, the four types, how arguments and return values work, and how to write them yourself. That is the foundation. Here are three things to do this week to lock it in:

  1. Write five user-defined functions from scratch: a temperature converter, a simple interest calculator, a vowel counter, a list flattener, and a grade classifier. Do not copy-paste; type every line.
  2. Rewrite one of those functions as a lambda and notice where it works well and where it does not. That comparison teaches you more than any explanation.
  3. Explore how functions power real applications. The 3.0 University guide on Python for automation, web scraping and APIs shows you exactly how the skills from this page translate into projects you can show employers.

Strong programming fundamentals, and understanding the types of functions in Python specifically, are the entry point to cybersecurity scripting, AI model development and blockchain application logic. If you are ready to take that further, explore the CEH v13 AI online course at 3.0 University, where Python is used hands-on in ethical hacking labs. You can also browse the full range of 3.0 University online certification courses in Cybersecurity, AI, Blockchain and Web3 to find the right next step for your goals.

Last updated: May 2025. Reviewed by the 3University editorial team.

We create, review, and maintain educational content covering Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain, Web3, and emerging technologies.

Read More Articles