BACSE101
Problem Solving Using Python
Introduction to Modular
Programming in Python
Introduction to Modular
Programming
What is Modular Programming?
Modular programming is a software design technique that breaks down a
large, complex program into smaller, independent, and manageable sub-
programs or modules. Each module is designed to perform a specific, well-
defined task.
•Analogy: Think of building a car. You don’t build the entire car at
once. Instead, you build separate components like the engine,
wheels, and chassis. Each component is a module that can be worked on
independently and then assembled to form the final product. Modular
programming follows this same principle.
Introduction to Modular
Programming
Why is it Important?
Modular programming offers several key advantages, especially for large
projects:
• Simplicity: It simplifies the development process by breaking a complex
problem into smaller, more manageable pieces.
• Reusability: Modules can be reused in different parts of the same program
or in entirely different programs, saving development time and effort.
• Maintainability: It’s easier to debug and maintain a program because you
can isolate and fix issues within a specific module without affecting the
entire program.
• Readability: Well-defined modules with clear names and functions make
the code easier to read and understand.
Fundamentals of Functions in
Python
In Python, the most basic form of a module is a function.
What is a Function?
A function is a named block of reusable code designed to perform a
specific action. It groups a series of statements into a single unit.
• Syntax for Defining a Function:
Fundamentals of Functions in
Python
–The def keyword is used to define a function.
–function_name is the name given to the function. It should be
descriptive.
–(parameter1, . . . ) are the inputs the function takes. These are optional.
–The colon : marks the end of the function header.
–The indented block of code that follows is the function body.
Return Value
• The return statement is used to exit a function and send a value back
to the code that called it.
• A function can have no return statement. In that case, it returns None
by default
Types of Functions Based on
Arguments and Return Values
Functions can be categorized into four types based on whether they accept
arguments and whether they return a value.
Function without Argument and without Return Value
• These functions perform a task and don’t require any input from the
calling code. They also don’t send any value back.
Types of Functions Based on
Arguments and Return Values
Function with Argument and without Return Value
• These functions accept input through arguments but do not return a
value. They are used for tasks that produce a side effect, like printing
to the console.
Types of Functions Based on
Arguments and Return Values
Function without Argument and with Return Value
• These functions perform a task without input and return a single
value. A common example is a function that generates a random
number.
Types of Functions Based on
Arguments and Return Values
Function with Argument and with Return Value
• These functions accept arguments and return a value. This is the most
common type of function, used for calculations or transformations.
Special Function Concepts
Inline Functions (Lambda Functions)
• A lambda function is a small, anonymous function defined with
the lambda keyword.
• It can take any number of arguments, but can only have one
expression.
• They are called ”inline” because they are often defined directly
where they are used.
Special Function Concepts
Built-in Functions
• Python comes with a rich set of built-in functions that are always
available for use. You don’t need to define them.
• Examples include print(), len(), type(), and input().
Special Function Concepts
Functions with Default Parameters
• You can assign a default value to a parameter. If an argument is not
provided for that parameter during the function call, the default
value is used.
Variable Scope: Local vs. Global
Scope of Variables
The scope of a variable determines where in your program the variable
is accessible.
Local Variables
• A local variable is defined inside a function.
• It can only be accessed from within that function.
• It is created when the function is called and is destroyed when the
function completes
Variable Scope: Local vs. Global
Global Variables
• A global variable is defined outside of any function, in the main
body of the script.
• It can be accessed from anywhere in the program, both inside and
outside functions.
• To modify a global variable from inside a function, you must use the
global keyword.
Recursive Functions
• A recursive function is a function that calls itself.
• Recursion is a powerful technique for solving problems that can be
broken down into smaller, self-similar sub-problems.
• Every recursive function must have a base case that stops the
recursion from running indefinitely.
• Example: Factorial Calculation The factorial of a non-negative
integer n, denoted by n!, is the product of all positive integers less
than or equal to n. n! = n× (n− 1) × (n− 2) × · · · × 1 For example, 5!
= 5 × 4 × 3 × 2 × 1 = 120.
The recursive definition is: n! = n× (n− 1)! Base Case: 0! = 1
Advanced Function Concepts
Function Arguments: Positional and Keyword
• Arguments passed to a function can be matched to parameters by
their position or by using their name. Using keyword arguments
improves code readability.
Advanced Function Concepts
Variable-Length Arguments (‘*args‘ and ‘**kwargs‘)
• These special syntaxes allow a function to accept a variable number
of arguments.
• *args collects a variable number of positional arguments into a
tuple.
• **kwargs collects a variable number of keyword arguments into a
dictionary.
Advanced Function Concepts
Inner Functions (Nested Functions)
• An inner function is a function defined inside another function.
• It can access variables from the outer function’s scope, a concept
known as a closure.
• They are not accessible from outside the parent function
Advanced Function Concepts
First-Class Functions
• In Python, functions are first-class objects, which means they can
be treated like any other variable.
• This allows you to:
–Assign a function to a variable.
–Pass a function as an argument to another function.
–Return a function as the result of another function.
Advanced Function Concepts
Type Hinting
• Type hinting is a modern Python feature that allows you to specify
the expected data types for function arguments and return values.
• While not enforced at runtime, it is a best practice that improves
code readability and allows for static analysis, helping to prevent
errors.
Advanced Function Concepts
Returning Multiple Values
• A function can return multiple values by packaging them into a
single object, most commonly a tuple. The caller can then unpack
these values into separate variables.
Advanced Function Concepts
Docstrings and the help() function
• A docstring is a vital part of a function’s documentation. It is a
string literal that provides a description of what the function does.
• You can access a function’s docstring programmatically using the
_ _ doc_ _ attribute or, more conveniently, with the built-in help()
function
Functions and Modules
• A module is a Python file that contains code, including functions,
classes, and variables. This is the core concept of modular
programming.
• You can use the functions from one module in another program using
the import statement.
Scope Revisited: nonlocal and
Default Argument Pitfalls
The nonlocal keyword
• When working with nested functions, the nonlocal keyword is used
to indicate that a variable being modified is not local to the inner
function, nor is it global. Instead, it belongs to an enclosing
function’s scope.
Scope Revisited: nonlocal and
Default Argument Pitfalls
The Mutable Default Argument Pitfall
• A common and important pitfall for beginners is using a mutable
object (like a list or dictionary) as a default argument.
• Python evaluates default arguments only once when the function is
defined. If the object is mutable, all subsequent calls that don’t
provide an argument will modify the same object.
• The solution is to use None as the default value and create a new
mutable object inside the function.