Functions and Modules in Python

Zero to Python Hero – Part 6/10: Functions and Modules in Python

The main concepts of Python programming are functions and modules. They enable us to separate code into smaller, reusable and more structured units to enhance readability and maintainability. Functions and modules assist in organizing logic and workflows just the way data structures can assist in the storage and arrangement of data.

This article shall discuss the Python function system in depth and explain the various functions of the Python language such as definitions, parameters, return values, special arguments, scope rules, and reusable modules. By the end, you will be able to create modular programs which are easier to debug, scale and share.

1. Defining and Calling Functions

A function is a called subroutine of code that carries out a particular task. You do not have to write the same code several times and can write it once in a function and use it anywhere.

def function_name(parameters):

    """Optional docstring describing the function"""

    # function body

    return value

Example: Simple Function

def greet():

    print("Hello, welcome to Python functions!")

greet()  # Function call

Output:

Hello, welcome to Python functions!

Why Use Functions?

  • Reusability: There is only one time to write but reuse it many times.
  • Readability: Break up complex code into meaningful parts.
  • Maintainability: Can update one function and not change everybody.

Real-World Example

Suppose a student grading system. Rather than calculating scores one-at-a-time, write a procedure:

def calculate_grade(marks):

    average = sum(marks) / len(marks)

    if average >= 90:

        return "A"

    elif average >= 75:

        return "B"

    else:

        return "C"

print(calculate_grade([89, 92, 95]))

2. Parameters and Return Values

Functions will usually have parameters (as inputs) and will have return values (outputs). E.g.: Parameters and Return.

def add(a, b):

    return a + b

result = add(5, 3)

print("Sum:", result)

Multiple Return Values

Python has a method of sending multiple values as a group:

def stats(numbers):

    return min(numbers), max(numbers), sum(numbers)/len(numbers)

low, high, avg = stats([10, 20, 30, 40])

print("Low:", low, "High:", high, "Avg:", avg)

3. Default Arguments, *args, **kwargs

Python provides flexible ways of handling arguments.

Default Arguments

You can assign default values to parameters.

def greet(name="Guest"):

    print(f"Hello, {name}!")

greet()          # Hello, Guest!

greet("Rajesh")  # Hello, Rajesh!

*args (Variable Positional Arguments)

Use *args to accept multiple positional arguments.

def total(*numbers):

    return sum(numbers)

print(total(10, 20, 30, 40))  # 100

**kwargs (Variable Keyword Arguments)

Use **kwargs to accept multiple keyword arguments.

def profile(**info):

    for key, value in info.items():

        print(f"{key}: {value}")

profile(name="Raj", age=30, city="Hyderabad")

4. Lambda Functions

A lambda function A lambda function is a small anonymous function implemented with the lambda keyword. They come in handy when you need to do things in the short run.

Syntax

lambda arguments: expression

Example

square = lambda x: x * x

print(square(5))  # 25

Real-World Example

Sorting with lambda:

students = [("Raj", 85), ("Sana", 92), ("Kiran", 78)]

students.sort(key=lambda s: s[1], reverse=True)

print(students)  # [('Sana', 92), ('Raj', 85), ('Kiran', 78)]

5. Scope and global/nonlocal

The scope is the visibility of variables within functions.

Local and Global Scope

x = 10  # Global

def func():

    x = 5  # Local

    print("Inside:", x)

func()

print("Outside:", x)

The global Keyword

To modify a global variable inside a function:

count = 0

def increment():

    global count

    count += 1

increment()

print(count)  # 1

The nonlocal Keyword

For modifying variables in nested functions:

def outer():

    x = "outer"

    def inner():

        nonlocal x

        x = "inner"

    inner()

    print(x)

outer()  # inner

6. Importing & Creating Modules

A module, as it is called, is a python file (.py) with functions, classes or variables.

Importing Modules

import math

print(math.sqrt(16))  # 4.0

Creating Your Own Module

Suppose you create a file mymath.py:

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

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

Now use it in another file:

import mymath

print(mymath.add(10, 5))  # 15

7. Writing Reusable Code

The reusable code is made up of functions and modules.

Tips for Reusability

  • Always maintain small and focused keep functions.
  • Write documentation.
  • Group like functions in modules.
  • Share packages broadly.

Example: Utility Module

# utils.py

def is_even(n): return n % 2 == 0

def factorial(n):

    return 1 if n == 0 else n * factorial(n-1)

Reusing in another script:

from utils import is_even, factorial

print(is_even(10))     # True

print(factorial(5))    # 120

Conclusion

Python program is based on functions and modules. You not only increase readability by splitting programs into smaller, clearly defined segments, but also minimize duplication and errors. Defs to complex parameter manipulation using the ideas of *args and/or **kwargs, anonymous lambda functions to structured modules – understanding these concepts leaves you a better and more efficient Python developer.

As with learning data structures, functions and modules must be used frequently. Keep it simple, develop utilities, and eventually package up your projects in reusable groups. After some time, you will have a code cleaner which is maintainable and can be used in the real world.

Author

  • Rajesh data analytics and AI

    Rajesh Yerremshetty is an IIT Roorkee MBA graduate with 10 years of experience in Data Analytics and AI. He has worked with leading organizations, including CarDekho.com, Vansun Media Tech Pvt. Ltd., and STRIKIN.com, driving innovative solutions and business growth through data-driven insights.

    View all posts
Spread the knowledge
 
  

Join the Discussion

Your email will remain private. Fields with * are required.