PYTHON • Intermediate

Python Functions

A function is a reusable block of code that performs a specific task. Functions make your program modular, readable, and easier to debug. In Python, you define functions with the def keyword. Once defined, you can call them any number of times.

Defining a Function

def greet():
    print("Hello from Varanasi!")

# Call the function
greet()   # Hello from Varanasi!
greet()   # Hello from Varanasi!

Functions with Parameters

Parameters let you pass data into a function.

def greet(name):
    print(f"Hello, {name}!")

greet("Ankit")    # Hello, Ankit!
greet("Priya")    # Hello, Priya!

Functions with Return Values

Use return to send a value back to the caller. If no return, the function returns None.

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

result = add(10, 20)
print(result)   # 30

# Return multiple values
def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([3, 1, 4, 1, 5])
print(low, high)   # 1 5

Types of Arguments

Python supports several ways to pass arguments — a favorite interview topic.

1. Positional Arguments

def info(name, age):
    print(f"{name} is {age} years old")

info("Ankit", 22)   # By position

2. Keyword Arguments

info(age=22, name="Ankit")   # Order doesn't matter

3. Default Arguments

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

greet("Ankit")               # Hello, Ankit!
greet("Priya", "Namaste")    # Namaste, Priya!

4. *args — Variable Positional Arguments

Accept any number of positional arguments as a tuple.

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

print(total(1, 2, 3))         # 6
print(total(10, 20, 30, 40))  # 100

5. **kwargs — Variable Keyword Arguments

Accept any number of keyword arguments as a dictionary.

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

profile(name="Ankit", age=22, city="Varanasi")

# Output:
# name: Ankit
# age: 22
# city: Varanasi

Lambda Functions (Anonymous)

Small, one-line functions without a name. Useful for short operations.

# Regular function
def square(x):
    return x ** 2

# Same as lambda
square = lambda x: x ** 2
print(square(5))   # 25

# Common with map, filter, sorted
nums = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, nums))
print(doubled)   # [2, 4, 6, 8, 10]

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

Scope of Variables

Variables have different scopes — where they can be accessed.

  • Local — inside a function, only accessible there.
  • Global — declared outside, accessible everywhere.
count = 0   # global

def increment():
    global count    # refer to global variable
    count += 1

increment()
print(count)   # 1
⚠ Best Practice

Avoid using global unless necessary. Prefer passing values as arguments and returning results — this makes code more predictable and testable.

Docstrings

Every function should have a documentation string. It explains what the function does.

def add(a, b):
    """Return the sum of two numbers."""
    return a + b

print(add.__doc__)   # Return the sum of two numbers.
help(add)            # Displays the docstring

Recursion — A Function That Calls Itself

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

print(factorial(5))   # 120

# Fibonacci
def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)

print([fib(i) for i in range(8)])   # [0, 1, 1, 2, 3, 5, 8, 13]

Real-World Example — Calculator

def calculate(a, b, op):
    """Perform basic arithmetic."""
    if op == "+":
        return a + b
    elif op == "-":
        return a - b
    elif op == "*":
        return a * b
    elif op == "/":
        return a / b if b != 0 else "Cannot divide by zero"
    else:
        return "Invalid operator"

print(calculate(10, 5, "+"))   # 15
print(calculate(10, 5, "*"))   # 50
print(calculate(10, 0, "/"))   # Cannot divide by zero
💡 Academy Tip

Rule of thumb: A function should do ONE thing and do it well. If a function is longer than 30 lines, split it into smaller functions.

📝 Try Yourself

Write three functions: is_even(n) that returns True if a number is even, find_max(a, b, c) that returns the largest of three numbers, and reverse_string(s) that returns the reversed string. Test each with 3 different inputs.

Quick Revision

  • Defined with def name():.
  • Parameters receive values; return sends a value back.
  • Argument types: positional, keyword, default, *args, **kwargs.
  • Lambda is a one-line anonymous function.
  • Scope: local vs global. Use global sparingly.
  • Docstrings document functions.
  • Recursion solves problems with self-similar structure.

Interview Questions

Q: Difference between *args and **kwargs?

A: *args collects extra positional arguments as a tuple. **kwargs collects extra keyword arguments as a dictionary. You can combine both: def f(*args, **kwargs).

Q: What is a lambda function? When should you use it?

A: A lambda is an anonymous, single-line function defined with the lambda keyword. Use it for short, throwaway operations — commonly with map(), filter(), and sorted(). Avoid lambdas for anything complex.

Q: What is the difference between local and global scope?

A: Local variables are declared inside a function and only accessible there. Global variables are declared outside any function and accessible throughout the file. Use global inside a function to modify a global variable.

Q: What does a function return if there's no return statement?

A: It returns None by default.

Q: What is recursion? Give an example.

A: Recursion is when a function calls itself to solve a smaller version of the same problem. Example: factorial(n) = n * factorial(n-1), with a base case factorial(0) = 1. Always ensure a base case to avoid infinite recursion.

Want to Master Python?

Join our Python course in Varanasi — practical classes and career support at our Sarnath centre.

Ask on WhatsApp
Chat with us