Placement Prep

Functions in Python with Examples: Complete Guide

Learn to define, call, and use Python functions with examples covering parameters, return values, lambda, and recursion for placement interview prep.

By FACE Prep Team 4 min read
python functions python-functions placement-prep coding-interview user-defined-functions

A Python function is a named block of code that runs only when called. Define it once with def, pass it data through arguments, and Python returns a value or executes a side effect.

Why Functions Exist in Python Code

The problem functions solve is repetition. Without one, the same logic has to appear everywhere it’s needed. Say you want to find all pairs of numbers in a list that sum to a target value:

list1 = [3, 6, 4, 9]
res = list1[0] + list1[1]
if res == 13:
    print(list1[0], list1[1])
# The same check has to be manually written for every other pair

Every new list, every new target means rewriting from scratch. One logic fix means touching a dozen places. A function collapses that entirely:

def find_pairs(lst, target):
    for i in range(len(lst)):
        for j in range(i + 1, len(lst)):
            if lst[i] + lst[j] == target:
                print(lst[i], lst[j])

find_pairs([3, 6, 4, 9], 13)
# prints: 4 9

The function version handles any list and any target without rewriting. Functions also make testing straightforward: you test find_pairs once with known inputs instead of tracking down all the places the same logic was duplicated. As the Python tutorial’s official function specification describes, a function definition associates a name with a code block and lets you call that block on demand.

Types of Functions in Python

Two categories cover all Python functions.

Built-in Functions

Pre-loaded in the interpreter. No import, no setup. The Python built-in functions reference documents 69 of them. The ones that show up most in placement coding rounds:

FunctionWhat it does
print()Outputs to the console
len()Returns the count of items in a sequence
sum()Adds all elements in an iterable
range()Generates a sequence of integers
type()Returns the data type of an object
sorted()Returns a new sorted list from any iterable
max() / min()Returns the largest or smallest element
int() / str() / float()Converts between data types

User-Defined Functions

Written with def. Every calculator program in Python that separates add, subtract, multiply, and divide into individual functions is a practical demonstration of user-defined functions.

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

print(add(5, 3))   # 8

How to Define and Call a Function

The process has three steps. For more context on putting these together in complete programs, the basic Python programs reference covers a wide variety of patterns.

Step 1: Define

def greet(name):          # 'name' is the parameter
    print(f"Hello, {name}.")

def keyword, function name, parentheses with parameters, colon. The indented block is the function body.

Step 2: Call

greet("Priya")            # "Priya" is the argument
# prints: Hello, Priya.

A function does nothing until you call it by name. Parameters (in the definition) receive arguments (in the call). The distinction matters when reading error messages: Python reports “takes 2 positional arguments but 3 were given” using the parameter count from the definition.

Step 3: Return a Value

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

result = multiply(4, 5)
print(result)             # 20

return stops execution and sends a value back to the caller. A function without a return statement returns None.

Four Types of Function Arguments

Python supports four argument forms. Each solves a distinct problem.

Positional Arguments

The most common type. Order is fixed: the first value maps to the first parameter, the second to the second.

def describe(branch, year):
    print(f"Branch: {branch}, Year: {year}")

describe("CSE", 3)
# Branch: CSE, Year: 3

Keyword Arguments

Name the parameters explicitly at call time. Order no longer matters.

describe(year=3, branch="ECE")
# Branch: ECE, Year: 3

Default Arguments

Set a fallback value in the definition. The caller can skip that argument when the default is appropriate.

def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}.")

greet("Priya")              # Hello, Priya.
greet("Priya", "Namaste")   # Namaste, Priya.

Variable-Length Arguments

*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. The sum of array problem is a case where *args appears naturally:

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

print(total(1, 2, 3, 4))    # 10
print(total(10, 20))         # 30

**kwargs is equally common when a function needs to accept a flexible set of named options:

def profile(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

profile(name="Ravi", branch="CSE", year=3)
# name: Ravi
# branch: CSE
# year: 3

Lambda, Nested Functions, and Recursion

Three patterns that appear in placement coding rounds and technical interview screens.

Lambda Functions

A lambda is a one-line anonymous function. Syntax: lambda parameters: expression. Common use: providing a sort key inline without defining a named function.

square = lambda x: x ** 2
print(square(4))    # 16

pairs = [(1, 3), (2, 1), (3, 2)]
pairs.sort(key=lambda x: x[1])
print(pairs)        # [(2, 1), (3, 2), (1, 3)]

Lambda works well for short throwaway logic passed as an argument. If the logic requires a condition, a loop, or more than one expression, a regular def is the cleaner choice.

Nested Functions

A function defined inside another function. The inner function has access to the outer function’s local variables.

def outer(text):
    def inner():
        return text.upper()
    return inner()

print(outer("hello"))    # HELLO

Recursive Functions

A recursive function calls itself until it reaches a base case. Alongside the greatest of three numbers pattern for conditional logic, factorial is the standard recursion example in placement tests:

def factorial(n):
    if n == 0:        # base case
        return 1
    return n * factorial(n - 1)

print(factorial(5))   # 120

How the call chain unwinds:

  • factorial(5) returns 5 * factorial(4)
  • factorial(4) returns 4 * factorial(3)
  • … down to factorial(0), which returns 1
  • Multiplying back: 1 * 2 * 3 * 4 * 5 = 120

Python’s default recursion depth handles standard placement problems without adjustment. For inputs in the thousands, an iterative loop is more reliable than deep recursion.

Recursive functions and lambda expressions follow the same call-and-return logic found in LLM pipeline code: function chaining, prompt routing, and retrieval steps all share that structure. TinkerLLM is a ₹299 sandbox where you apply these Python patterns in real LLM API calls, not just read about them.

Primary sources

Frequently asked questions

What is the difference between a parameter and an argument in Python?

A parameter is the variable in the function definition. An argument is the actual value passed at call time. In `def greet(name)`, `name` is the parameter; in `greet('Priya')`, `'Priya'` is the argument.

Can a Python function return more than one value?

Yes. Write `return a, b` and Python packs the values into a tuple automatically. Unpack on the calling side with `x, y = my_function()`. This is cleaner than returning a list for fixed-size results.

What is a lambda function and when should I use it?

A lambda is a one-line anonymous function defined with the `lambda` keyword, such as `lambda x: x**2`. Use it for short throwaway logic like sort keys or filter conditions. For anything longer than a single expression, a regular `def` is clearer.

What is recursion in Python and why is there a recursion limit?

A recursive function calls itself until it hits a base case. Python's default recursion limit is 1,000 calls, inspectable with `sys.getrecursionlimit()`. For large inputs, an iterative loop is usually safer than deep recursion.

What happens if a function has no return statement?

Python returns `None` implicitly. This is equivalent to writing `return None` at the end. If you print the return value of such a function, you will see `None` in the output.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF