Theory of Intelligence
PYTHON PROGRAMMING•Control Flow And Functions•Modules And Packages•3.1 Modules & import

3.1.1 Writing Your Own Module

Subtopics: Writing Your Own Module, Import Styles and __name__ == \"__main__\".

3.1.1 Writing Your Own Module

Modular programming is a technique used to divide a program into smaller, manageable, and reusable pieces called modules. By breaking a program into modules, developers can work on different parts independently and reuse code efficiently. This approach simplifies managing complex programs and promotes code reuse.

The main Function

The main function in Python defines where the program should start. It's usually placed in a block that checks if the script is being run directly or imported as a module.

Example: Here's a simple example:

PYTHON
# main.py
def main():
    print("This is the main function.")

if __name__ == "__main__":
    main()

Explanation: In this example, the main() function will only run if the script is executed directly, not when it's imported elsewhere. This setup is useful in larger projects that have multiple modules.

Tidbits

lightbulb

Using the main function with modules helps keep your code organized, making it easier to maintain. Always use the main function to define the starting point of your program, and use modules to separate different parts of your code.

DO YOU KNOW?

lightbulb

Python's standard library is made up of hundreds of modules that you can be used to perform common tasks, like working with dates, generating random numbers, or reading files.

Class Activity

Create a Python module named calculator.py that includes two functions:

  1. add(a, b) - This function should return the sum of two numbers.
  2. subtract(a, b) - This function should return the difference between two numbers.

Then, write a script named main.py that imports your calculator module and uses these functions to perform the following:

  • Print the result of adding 1515 and 88.
  • Print the result of subtracting 1010 from 2525.

Make sure to run your main.py script and verify that the output is correct.

Discuss theoretical concepts, mathematical formulas, and architectural foundations.

Supports inline code with `backticks`
No comments yet. Be the first to start the discussion!