Introduction to Modules

Overview

A module is a file that contains code. If you are creating a huge program with many lines of code and various operations, to better organize your code, you can create sections (of code) and put each section in its own module. That way, you would know what module contains what type(s) of operation(s).

A module is a computer file with the extension .py. When you start a Python project, you must create a module, a file with an appropriate name and the .py extension. That first module is referred to as the main module. Of course, you can use any text editor, such as Notepad, to create the file. If you are working in Visual Studio Code, to start a module, on the main menu, click File -> New File. Type your code, then save the file with the .py extension.

If you are working in Microsoft Visual Studio, it makes it very easy to create a module, which is done from the Add New Item dialog box, where you would select the Empty Python File option, give a name to the file (you don't need to add an extension to the file), and click Add (or press Enter).

If you are using Microsoft Visual Studio and create a Python project, the studio would create a default module, named the main module, with the same name you gave to the project. When necessary, you can add other modules.

Practical LearningPractical Learning: Introducing Modules

  1. Start Microsoft Visual Studio
  2. Create a new Python Application named LoanEvaluation1
  3. In the empty document, type:
    print("Loans Categories")
    print("Our company provides the following categories of loans:")
    print('1. Personal Loan')
    print('2. Car Financing')
    print('3. Boat Financing')
    print('4. Furniture Purchase')
    print("========================================================")
  4. To execute the application, on the main menu, click Debug -> Start Without Debugging:
    Loans Categories
    Our company provides the following categories of loans:
    1. Personal Loan
    2. Car Financing
    3. Boat Financing
    4. Furniture Purchase
    ========================================================
    Press any key to continue . . .
  5. Press Enter to close the window and return to your programming environment
  6. To create a new module, in the Solution Explorer, right-click the second LoanEvaluation1 -> Add -> New Item...
  7. In the middle list of the Add New Item dialog box, click Empty Python File
  8. Change the file name to conclusions

    Add New Item

  9. Click Add
  10. In the empty document, type the following lines:
    print("Please contact us for any information about loans.")
    print('Contact details can be found on our website.')
  11. Click the LoanEvaluation1.py tab to access its document

Importing a module

If you have a module, whether one you created or one that was provided to you, to use the code of that module in another module, you must import it. To do this, in the document where you want to use the code of the module, type import followed by the name of the module (and an optional semi-colon, which is neither necessary nor required). If you want the code of the module to be executed before any code in the file where you are importing, write the importing line in the top section of the document. If you want the code of the module to be executed after a certain section, write the importing line after that section.

Practical LearningPractical Learning: Importing a Module

  1. In the LoanEvaluation1.py document, add the following line:
    print("Loans Categories")
    print("Our company provides the following categories of loans:")
    print('1. Personal Loan')
    print('2. Car Financing')
    print('3. Boat Financing')
    print('4. Furniture Purchase')
    print('-------------------------------------------------------')
    
    import conclusions
    
    print("========================================================")
  2. To execute the application to see the result, on the main menu, click Debug -> Start Without Debugging. This would produce:
    Loans Categories
    Our company provides the following categories of loans:
    1. Personal Loan
    2. Car Financing
    3. Boat Financing
    4. Furniture Purchase
    -------------------------------------------------------
    Please contact us for any information about loans.
    Contact details can be found on our website.
    ========================================================
    Press any key to continue . . .
  3. Press Enter to close the window and return to your programming environment
  4. To start another module, on the main menu, click Project -> Add New Item...
  5. In the middle list of the Add New Item dialog box, click Empty Module
  6. Change the file name to introduction
  7. Click Add
  8. In the empty document, type the following lines:
    print("Watts' A Loan")
    print('About Us -|- Contact Us')
    print('-------------------------------------------------------')
  9. Click the LoanEvaluation1.py tab to access its document
  10. In the document, add the following line:
    import introduction
    
    print("Loans Categories")
    print("Our company provides the following categories of loans:")
    print('1. Personal Loan')
    print('2. Car Financing')
    print('3. Boat Financing')
    print('4. Furniture Purchase')
    print('-------------------------------------------------------')
    
    import conclusions
    
    print("========================================================")
  11. To execute the application to see the result, on the main menu, click Debug -> Start Without Debugging. This would produce:
    Watts' A Loan
    About Us -|- Contact Us
    -------------------------------------------------------
    Loans Categories
    Our company provides the following categories of loans:
    1. Personal Loan
    2. Car Financing
    3. Boat Financing
    4. Furniture Purchase
    -------------------------------------------------------
    Please contact us for any information about loans.
    Contact details can be found on our website.
    ========================================================
    Press any key to continue . . .
  12. Press Enter to close the window and return to your programming environment
  13. To start another module, on the main menu, click Project -> Add New Item...
  14. In the middle list of the Add New Item dialog box, click Empty Module (it should be selected already).
    Change the file name to loanDetails
  15. Press Enter
  16. In the empty document, type the following line:
    print("Loan Application")

A Variable in a Module

You can declare a variable in a module to prepare that variable to be accessed and used in another module. You can simply declare the variable in the document of the module, just like we have declared variables so far. If you want, you can use that variable in the same module.

Practical LearningPractical Learning: Declaring Variables in a Module

  1. To declare and use some variables, change the loanDetails document as follows:
    print("Loan Application")
    fname : str = "Justine"
    lname : str = "Cranston"
    loan_amount : float = 2500
    interest_rate : float = 12.25  # %
    periods : int = 36           # Number of months
    
    print('First Name:      ', fname)
    print('Last Name:       ', lname)
    print('Loan Amount:     ', loan_amount)
    print('Interest Rate:   ', interest_rate)
    print('Periods:         ', periods)
  2. Click the LoanEvaluation1.py tab to access its document
  3. In the document, add the following line:
    import introduction
    import loanDetails
    
    print('-------------------------------------------------------')
    print("Loans Categories")
    print("Our company provides the following categories of loans:")
    print('1. Personal Loan')
    print('2. Car Financing')
    print('3. Boat Financing')
    print('4. Furniture Purchase')
    print('-------------------------------------------------------')
    
    import conclusions
    
    print("========================================================")
  4. To execute the application to see the result, on the main menu, click Debug -> Start Without Debugging. This would produce:
    Watts' A Loan
    About Us -|- Contact Us
    -------------------------------------------------------
    Loan Application
    First Name:      Justine
    Last Name:       Cranston
    Loan Amount:     2500
    Interest Rate:   12.25
    Periods:         36
    -------------------------------------------------------
    Loans Categories
    Our company provides the following categories of loans:
    1. Personal Loan
    2. Car Financing
    3. Boat Financing
    4. Furniture Purchase
    -------------------------------------------------------
    Please contact us for any information about loans.
    Contact details can be found on our website.
    ========================================================
    Press any key to continue . . .
  5. Press Enter to close the window and return to your programming environment
  6. To start another module, on the main menu, click Project -> Add New Item
  7. In the middle list of the Add New Item dialog box, click Empty Module (it should be selected already).
    Change the file name to loanEvaluation
  8. Click Add
  9. In the empty document, type the following line:
    import loanDetails
    
    iRate : float = 100.00
    loan_in_years : float = 12
    interest_amount : float = iRate * loan_in_years
    future_value : float = interest_amount

A Variable from a Module

If you declare a variable in a module and you want to access that variable in a module, you have two options. You can first import the module as we saw in previous sections. To access the variable in the different module, type the name of the module, a period, and the name of the variable. The use of that period is referred to as qualification. This means that, with the period operator, you are qualifying the name of the variable as belonging to the module. As an alternative, you can use a keyword named from. The formula to follow is:

from module-name import variable-name[;]

If you need to import more than one variable, type their names after import and separate them with commas. After doing that, you can use the name of the variable and don't qualify it. In the same way, you can use a variable contained in a module that someone else created.

Practical LearningPractical Learning: Importing Variables from a Module

  1. To access the variables by qualifying them, change the loanEvaluation document as follows:
    import loanDetails
    
    iRate : float = loanDetails.interest_rate / 100.00
    loan_in_years : float = loanDetails.periods / 12
    interest_amount : float = loanDetails.loan_amount * iRate * loan_in_years
    future_value : float = loanDetails.loan_amount + interest_amount
  2. Click the LoanEvaluation1.py tab to access its document
  3. To access variables from a module, change the document as follows:
    import introduction
    import loanDetails
    from loanEvaluation import future_value
    from loanEvaluation import interest_amount, iRate
    
    print('-------------------------------------------------------')
    print('Interest Rate:   ', iRate)
    print('Interest Amount: ', interest_amount)
    print('Future Value:    ', future_value)
    
    print('-------------------------------------------------------')
    print("Loans Categories")
    print("Our company provides the following categories of loans:")
    print('1. Personal Loan')
    print('2. Car Financing')
    print('3. Boat Financing')
    print('4. Furniture Purchase')
    print('-------------------------------------------------------')
    
    import conclusions
    print("=======================================================")
  4. To execute the application to see the result, on the main menu, click Debug -> Start Without Debugging. This would produce:
    Watts' A Loan
    About Us -|- Contact Us
    -------------------------------------------------------
    Loan Application
    First Name:       Justine
    Last Name:        Cranston
    Loan Amount:      2500
    Interest Rate:    12.25
    Periods:          36
    -------------------------------------------------------
    Interest Rate:    0.1225
    Interest Amount:  918.75
    Future Value:     3418.75
    -------------------------------------------------------
    Loans Categories
    Our company provides the following categories of loans:
    1. Personal Loan
    2. Car Financing
    3. Boat Financing
    4. Furniture Purchase
    -------------------------------------------------------
    Please contact us for any information about loans.
    Contact details can be found on our website.
    =======================================================
    Press any key to continue . . .
  5. Press Enter to close the window and return to your programming environment

Intrduction to Built-In Modules

Intrduction

A feature or behavior is referred to as "built-in" if either it is part of the system or it is a ready-made external feature or behavior that can be brought in and made part of the system. Most or all computer languages include various types of built-in features and behaviors. Some other features and behaviors can/should/must be imported into the language and be used directly without changing them.

To assist you with your applications, the Python language ships with many modules, built-in modules, you can use in your code. If those modules are not enough, you can acquire other modules one way or another and use them in your applications. Little by little, you will know where to find modules on the Internet and how to install them to use in your applications.

Once you are aware of a module, to use it in a document, type import followed by the name of the module.

Introduction to Built-In Variables

As we learned already, you can use a variable from a module. This can be done by first importing the module. To access the variable, type the name of the module, followed by a period, and followed by the name of the variable. You can then use the variable as we have done so far with other variables.

If a module was provided to you and that module contains a variable you want to use in your code, in the top section of your document, type import followed by the name of the module. Then, in the same document, to access the variable, you can type the name of the module, a period, and the name of the variable. We also saw that you can use the from keyword to specify the particular name of the variable you want to import.

To assist you in creating applications, the Python language includes some variables that are already created (declared and appropriately initialized) so that you can use them in your code. There are a few of those variables and they are used for different goals. By convention, the names of all the special built-in variables start and end with two underscores.

The Main Module of an Application

Obviously when you start a Python project, you must create at least one file (or module) on which you will write your Python code. If you are working from a command prompt or a terminal writing your code in a text editor such as Notepad, or you are working in Visual Studio Code, you will have to create a file and save it with the .py extension. If you are creating your application in Microsoft Visual Studio and create your application from a template, the studio would create a default file for you.

The first Python file or module is referred to as the main module. To help you identify that variable, Pyhon calls that module, or refers to it, with the name __main__. To access that module in your code, use its name as a string; that is, include it in single or double-quotes: '__main__' or "__main__".

The Name of a Module

When you work on a Python project, you usually create or add many files (modules). We saw that one of those files is the main or central module. The Python interpreter or compiler gives a default name (__main__) to that module. Sometimes when you are organizing your modules, you may want each module to contain a certain category of code or to perform some specific operations. When you are creating your modules, to be able to identify the modules throughout your project, you can create a virtual name for one of the modules, some of the modules, or all modules. To let you do this, the Python language provides a variable named __name__.

To create a name for a module, in the top section of its document, type __name__ and assign a string to the variable. The name can be the same name as the file or any name you want. Here is an example:

__name__ = "flowers"

In the same way, you can name any module you want. If you don't create a name for a module, its name becomes the name of its file. Either way, eventually, you can write code that acts only based on the name of the module and not work if the name of the module is not a certain one.

Practical LearningPractical Learning: Naming the Modules

  1. Click the loanEvaluation.py tab to access its document and name it as follows:
    __name__ = "LoanEvaluation_UsedToPerformCalculations"
    
    import loanDetails
    
    iRate : float = loanDetails.interest_rate / 100.00
    loan_in_years : float = loanDetails.periods / 12
    interest_amount : float = loanDetails.loan_amount * iRate * loan_in_years
    future_value : float = loanDetails.loan_amount + interest_amount
    
    print("Module Name: ")
    print(__name__)
    print('-+---+---+---+---+---+---+---+---+---+---+---+---+---+-')
  2. Click the loanDetails.py tab and name it as follows:
    __name__ = "Loan_Details_ProvidesMoreInformation"
    
    print("Loan Application")
    fname : str = "Justine"
    lname : str = "Cranston"
    loan_amount : float = 4750
    interest_rate : float = 14.50  # %
    periods : int = 42           # Number of months
    
    print('First Name:      ', fname)
    print('Last Name:       ', lname)
    print('Loan Amount:     ', loan_amount)
    print('Interest Rate:   ', interest_rate)
    print('Periods:         ', periods)
    
    print("Module Name: ")
    print(__name__)
    print('-+---+---+---+---+---+---+---+---+---+---+---+---+---+-')
  3. Click the conclusions.py tab and change its document as follows:
    print("Please contact us for any information about loans.")
    print('Contact details can be found on our website.')
    
    print("Module Name: ")
    print(__name__)
    print('-+---+---+---+---+---+---+---+---+---+---+---+---+---+-')
  4. Click the introduction.py tab and change its document as follows:
    print("Watts' A Loan")
    print('About Us -|- Contact Us')
    print('-------------------------------------------------------')
    
    print("Module Name: ")
    print(__name__)
    print('-+---+---+---+---+---+---+---+---+---+---+---+---+---+-')
  5. Click the LoanEvaluation1.py tab and name it as follows:
    import introduction
    import loanDetails
    from loanEvaluation import future_value
    from loanEvaluation import interest_amount, iRate
    
    __name__ = "__main__"
    
    print('-------------------------------------------------------')
    print('Interest Rate:   ', iRate)
    print('Interest Amount: ', interest_amount)
    print('Future Value:    ', future_value)
    print('-------------------------------------------------------')
    print("Loans Categories")
    print("Our company provides the following categories of loans:")
    print('1. Personal Loan')
    print('2. Car Financing')
    print('3. Boat Financing')
    print('4. Furniture Purchase')
    print('-------------------------------------------------------')
    
    import conclusions
    
    print("========================================================")
    
    print("Module Name: ")
    print(__name__)
    print('-+---+---+---+---+---+---+---+---+---+---+---+---+---+-')
  6. To execute the application to see the result, on the main menu, click Debug -> Start Without Debugging. This would produce:
    Watts' A Loan
    About Us -|- Contact Us
    -------------------------------------------------------
    Loan Application
    First Name:       Justine
    Last Name:        Cranston
    Loan Amount:      2500
    Interest Rate:    12.25
    Periods:          36
    Module Name:
    Loan_Details_ProvidesMoreInformation
    -+---+---+---+---+---+---+---+---+---+---+---+---+---+-
    Module Name:
    LoanEvaluation_UsedToPerformCalculations
    -+---+---+---+---+---+---+---+---+---+---+---+---+---+-
    -------------------------------------------------------
    Interest Rate:    0.1225
    Interest Amount:  918.75
    Future Value:     3418.75
    -------------------------------------------------------
    Loans Categories
    Our company provides the following categories of loans:
    1. Personal Loan
    2. Car Financing
    3. Boat Financing
    4. Furniture Purchase
    -------------------------------------------------------
    Please contact us for any information about loans.
    Contact details can be found on our website.
    Module Name:
    conclusions
    -+---+---+---+---+---+---+---+---+---+---+---+---+---+-
    =======================================================
    Module Name:
    __main__
    -+---+---+---+---+---+---+---+---+---+---+---+---+---+-
    Press any key to continue . . .
  7. Press Enter to close the window and return to your programming environment

Identifying an Operating System

Obviously when you are developing an application, you are working in a particular operating system, and operating systems have different behaviors. To help in identifying the operating system on which a person is working and perhaps to perform some operating system-related operations on the computer, the Python language provides a module named os. Before using it, you can import it in the top section of your file.

To help you identify the operating system on which your application is running, the os module is equipped with a variable named name. You can access it to get the name of the operating system. Here is an example:

import os

print("Current Operating System: ", os.name)

Here is an example of what this would produce (the application was executed in Microsoft Windows 10 Professional):

Current Operating System:  nt
=================================
Press any key to continue . . .

Introduction to Packages

Organizing Modules

We saw that, one way to organize your code is to divide sections of code or groups of operations in modules so that each module would have a specific mission. You can still end up with operations that can be grouped in similarities of missions. A package is a group of modules. This means that a package is a way to organize modules in groups. There is no strict way or policy to organize your modules. It is up to you to decide what module goes in what package.

Creating a Package

As you may imagine, a package is like a computer folder: its purpose is to contain or represent a group of files (modules). The fundamental difference between a Python package and a folder is that a package cannot be empty. A Python package must contain at least one module named __init__.py. If you are manually creating the files for your application, you would have to create the package yourself. If you are working in Microsoft Visual Studio, it makes it easy to create a package and its __init__.py file from the Add New Item dialog box.

Practical LearningPractical Learning: Introducing Packages

  1. To create a package, in the Solution Explorer, right-click the second LoanEvaluation1 node (that of the project) -> Add -> New Item...
  2. In the middle list of the Add New Item dialog box, click Python Package
  3. Change the file Name to Exercise

    Add New Item

  4. Click Add.
    Notice that the package contains a default module named __init__.py

    Solution Explorer - Package

Populating a Package

A package is a container used to organize code. After creating a package, you can add modules to it. Besides modules, you can create folders in a package. You can then add other modules to folders inside an existing package. Besides modules and folders, you can create one or more packages inside a package. Such a sub-package becomes a true package and enjoys all the characteristics of a package.

Practical LearningPractical Learning: Populating a Package

Importing Code from a Package

Obviously the most important interest you have in a package is its content. To access code of a package in a module outside that package, you must import it. As we saw already, to import, type import, then:

Practical LearningPractical Learning: Populating a Package

  1. Click the LoanEvaluation1.py tab and name it as follows:
    import introduction
    import loanDetails
    from loanEvaluation import future_value
    from loanEvaluation import interest_amount, iRate
    
    __name__ = "__main__"
    
    print('-------------------------------------------------------')
    print('Interest Rate:   ', iRate)
    print('Interest Amount: ', interest_amount)
    print('Future Value:    ', future_value)
    print('-------------------------------------------------------')
    
    print("Loans Categories")
    print("Our company provides the following categories of loans:")
    print('1. Personal Loan')
    print('2. Car Financing')
    print('3. Boat Financing')
    print('4. Furniture Purchase')
    print('-------------------------------------------------------')
    
    import conclusions
    print("=======================================================")
    
    print("Module Name: ")
    print(__name__)
    print('-+---+---+---+---+---+---+---+---+---+---+---+---+---+-')
    
    import Exercise
    print(Exercise.ceo)
  2. To execute the application to see the result, on the main menu, click Debug -> Start Without Debugging. This would produce:
    Watts' A Loan
    About Us -|- Contact Us
    -------------------------------------------------------
    Loan Application
    First Name:       Justine
    Last Name:        Cranston
    Loan Amount:      2500
    Interest Rate:    12.25
    Periods:          36
    Module Name:
    Loan_Details_ProvidesMoreInformation
    -+---+---+---+---+---+---+---+---+---+---+---+---+---+-
    Module Name:
    LoanEvaluation_UsedToPerformCalculations
    -+---+---+---+---+---+---+---+---+---+---+---+---+---+-
    -------------------------------------------------------
    Interest Rate:    0.1225
    Interest Amount:  918.75
    Future Value:     3418.75
    -------------------------------------------------------
    Loans Categories
    Our company provides the following categories of loans:
    1. Personal Loan
    2. Car Financing
    3. Boat Financing
    4. Furniture Purchase
    -------------------------------------------------------
    Please contact us for any information about loans.
    Contact details can be found on our website.
    Module Name:
    conclusions
    -+---+---+---+---+---+---+---+---+---+---+---+---+---+-
    =======================================================
    Module Name:
    __main__
    -+---+---+---+---+---+---+---+---+---+---+---+---+---+-
    Other services we provide are: Business plans, business advertizing, and website service(website design, development, management, etc).
    Catherine Watts - Owner, General Manager
    Press any key to continue . . .
  3. Press Enter to close the window and return to your programming environment

Introduction to Built-In Packages

Introduction

To assist you when creating your applications, various packages are available to you. Some packages are already available with your installation of Python. Some other packages must be installed.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2021-2024, FunctionX Tuesday 06 August 2024, 16:58 Next