0% found this document useful (0 votes)
4 views

II Unit Modular Approach

The document discusses modular programming in Python, emphasizing the benefits of code organization, reusability, and maintainability through the use of independent modules. It details how to create and import modules, implement testing techniques, and utilize string methods effectively. Additionally, it explains the significance of underscores in Python for various purposes such as naming conventions and value handling.

Uploaded by

MyDream 4U
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

II Unit Modular Approach

The document discusses modular programming in Python, emphasizing the benefits of code organization, reusability, and maintainability through the use of independent modules. It details how to create and import modules, implement testing techniques, and utilize string methods effectively. Additionally, it explains the significance of underscores in Python for various purposes such as naming conventions and value handling.

Uploaded by

MyDream 4U
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

A MODULAR APPROACH TO PROGRAM ORGANIZATION IN PYTHON

Modular programming in Python involves structuring code into independent,


reusable modules. Each module is a separate file containing functions, classes, or
variables related to a specific task or functionality. This approach enhances code
organization, maintainability, and reusability
Benefits of Modular Programming

• Improved Organization:

Modules break down a large program into smaller, manageable parts, making it
easier to understand and navigate.

• Code Reusability:
Modules can be imported and used in multiple program parts or in different
projects, reducing code duplication.
• Namespace Management:

Each module has its namespace, preventing naming conflicts between different parts
of the code.

• Enhanced Maintainability:
Changes or bug fixes in one module are less likely to affect other parts of the
program, simplifying maintenance.
• Testability:
Individual modules can be tested independently, making it easier to ensure the
correctness of the code.

IMPLEMENTING MODULAR PROGRAMMING

• Create Modules:
Divide the program's functionality into logical units and create separate Python files
(.py) for each module.

• Define Functions and Classes:

Within each module, define functions and classes that implement the module's
specific tasks.
IMPORTING MODULES IN PYTHON

Use the import statement to access the functions and classes defined in other
modules. There are several ways to use import:

• import module_name: Imports the entire module.


• from module_name import function_name: Imports a specific function from
the module.
• from module_name import *: Imports all names defined in the module (not
recommended for large projects).

• import module_name as alias: Imports the module with an alias.


Importing entire module

This imports the entire module, and its contents can be accessed using dot notation.

For example:
import math
print(math.sqrt(25)) # Output: 5.0

Importing specific names from a module.

This imports only the specified names from the module, and they can be used
directly without dot notation.

For example:

from math import pi, sqrt


print(pi) # Output: 3.141592653589793
print(sqrt(16)) # Output: 4.0

Importing all names from a module.


This imports all names from the module, but it is generally discouraged as it can lead
to namespace conflicts and make code harder to read. Importing a module with an
alias.

Importing a module with an alias.

This imports the module with a different name, which can be useful for shortening
long module names or avoiding conflicts
For example:

import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3]})
print(df)

Importing Specific Functions


from math import pi

print(pi)
Output

3.141592653589793

Importing Everything from a Module (*)


from math import *

print(pi) # Accessing the constant 'pi'

print(factorial(6)) # Using the factorial function

Output
3.141592653589793
720

DEFINING /CREATING OWN MODULES IN PYTHON


A module in Python is a file containing Python definitions and statements, which can
include variables, functions, and classes. Modules serve to organize code into
reusable blocks. The filename of the module, with the .py extension, becomes the
module name.

Creating a Module
• Write Python code: Create a new file (e.g., my_module.py) and define the
functions, classes, or variables you want to include in your module.

Save the file: Save the file with a .py extension. This file is now a module.

Using a Module

• Import the module: In another Python script or interactive session, import the
module using the import statement.
Import specific items: You can import specific functions or classes from a module
using the from ... import ... statement.

Rename a module: When importing a module, you can rename it using the as
keyword.

TESTING CODE SEMI-AUTOMATICALLY IN PYTHON

Semi-automatic testing in Python involves a blend of manual and automated


techniques to validate code correctness. It often focuses on leveraging built-in tools
or simple scripts to streamline the testing process without fully automating it. Here's
an overview of common approaches

1. Doctests

Doctests allow embedding test cases directly within the docstrings of functions,
classes, or modules. These tests are written like interactive Python interpreter
sessions, making them easy to understand and maintain.
Doctests are particularly useful for testing small code snippets and providing
executable documentation

2. Assert Statements

Assert statements are a simple way to check for expected outcomes within
your code. While not a comprehensive testing framework, they can be strategically
placed to validate assumptions during development.

Assert statements are helpful for catching errors early in the development process.

3. Basic Test Functions


Simple test functions can be written to group related assertions and provide
more structured testing. While this approach lacks the features of a full-fledged
testing framework, it offers a more organized way to manage tests than scattered
assert statements.
4. Unit test

Python's unit test module provides a more structured approach to testing,


allowing you to create test cases, test suites, and fixtures.

5. Generating Test Data


Generating test data, either manually or with scripts, can help test functions
with various inputs. For example, one could use random data generation to test the
robustness of a function.
This approach is particularly useful for testing functions that handle collections
or have many possible inputs.
GROUPING FUNCTIONS USING METHODS IN PYTHON

Grouping functions in Python involves organizing related functionalities


together for better code structure and maintainability. This can be achieved through
various methods, such as using classes, modules, or even nested functions
Using Classes

Classes can encapsulate functions (methods) that operate on shared data or


serve a common purpose.

Using Modules

Modules allow grouping functions into separate files, promoting modularity and
reusability.
These functions can be used in another script after importing the module.

CALLING METHODS THE OBJECT-ORIENTED WAY IN PYTHON


In Python, methods are called on objects using dot notation. This involves
writing the object's name, followed by a dot (.), and then the method's name, along
with any necessary arguments in parentheses.
In this example, my_dog is an object of the Dog class. The bark() method is
called on my_dog using my_dog.bark(). The self parameter in the method definition
refers to the instance of the class (in this case, my_dog). When calling the method,
self is automatically passed, so you don't need to include it in the method call

EXPLORING STRING METHODS IN PYTHON


Python strings are sequences of characters and offer a variety of built-in methods for
manipulation. These methods provide functionalities ranging from case conversion
and string searching to formatting and splitting.

Common String Methods


Case Conversion:

upper(): Converts the string to uppercase.

lowe(): Converts the string to lowercase.


capitalize(): Capitalizes the first character of the string.

title(): Converts the first character of each word to uppercase.

casefold(): Converts to case-folded strings, useful for case-insensitive comparisons.

swapcase(): Swaps the case of all characters in the string.

Searching and Counting:


❖ count(substring): Returns the number of occurrences of a substring.
❖ find(substring): Returns the index of the first occurrence of a substring, or -1 if
not found.
❖ index(substring): Returns the index of the first occurrence of a substring,
raising an error if not found.
❖ rfind(substring): Returns the highest index of the substring if found, and if not
found, it returns -1.
❖ rindex(substring): Returns the highest index of the substring if found, and if not
found, it raises an exception.
Checking String Properties:

✓ startswith(prefix): Checks if the string starts with a given prefix.


✓ endswith(suffix): Checks if the string ends with a given suffix.
✓ isalnum(): Returns true if all characters in the string are alphanumeric.
✓ isalpha(): Returns true if all characters in the string are alphabetic.
✓ isdigit(): Returns true if all characters in the string are digits.
✓ isspace(): Returns true if all characters in the string are whitespace.
✓ islower(): Returns true if all cased characters in the string are lowercase.
✓ isupper(): Returns true if all cased characters in the string are uppercase.
✓ istitle(): Returns true if the string is a titlecased string.
✓ isprintable(): Returns true if all characters in the string are printable.
✓ isnumeric(): Returns true if all characters in the string are numeric.
✓ isidentifier(): Returns true if the string is a valid identifier.

Modifying Strings:

❖ strip(): Removes leading and trailing whitespace.


❖ lstrip(): Removes leading whitespace.
❖ rstrip(): Removes trailing whitespace.
❖ replace(old, new): Replaces all occurrences of a substring with another string.

Splitting and Joining:

✓ split(separator): Splits the string into a list of substrings based on a separator.


✓ join(iterable): Joins elements of an iterable (e.g., list, tuple) into a single string.
✓ partition(separator): Splits the string into three parts based on the first
occurrence of the separator and returns a tuple.
✓ rpartition(separator): Splits the string into three parts based on the last
occurrence of the separator and returns a tuple.
✓ splitlines(): Splits the string at line boundaries and returns a list of lines.

Formatting:

✓ center(width, fillchar): Returns a centered string of a specified width.


✓ ljust(width, fillchar): Returns a left-justified string of a specified width.
✓ rjust(width, fillchar): Returns a right-justified string of a specified width.
✓ zfill(width): Pads the string with leading zeros to a specified width.
✓ format(): Formats a string using placeholders.
✓ format_map(): Formats a string using a dictionary-like object for substitutions.

Other Methods:
❖ len(): Returns the length of a string.
❖ str(): Returns a string representation of an object.
❖ encode(): Returns an encoded version of the string.
❖ translate(): Returns a translated string based on a translation table.
❖ maketrans(): Returns a translation table for use with the translate method.

UNDERSCORE IN PYTHON

The underscore (_) serves multiple purposes in Python:

• Ignoring values: It can be used as a throwaway variable when unpacking or


iterating, indicating that the value is not meant to be used

Last expression result: In the interactive interpreter, the underscore holds the result
of the last evaluated expression

Number formatting: It can be used to group digits in numbers for better


readability.

Naming conventions:
• Single leading underscore (_variable): Indicates a variable or method is
intended for internal use within a module or class (non-public). It's a
convention, not enforced by Python.

• Double leading underscore (\_\_variable): Triggers name mangling, making


the attribute harder to access from outside the class. It's used to prevent
naming conflicts in subclasses.
• Double leading and trailing underscores (\_\_variable\_\_): Denotes special
methods or attributes used by Python (e.g., \_\_init\_\_, \_\_name\_\_). Avoid
using this form for user-defined names

Internationalization and localization:


• The underscore is sometimes used as a function name alias for translation
lookups.

You might also like