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:
# 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
lightbulbUsing the
mainfunction with modules helps keep your code organized, making it easier to maintain. Always use themainfunction to define the starting point of your program, and use modules to separate different parts of your code.
DO YOU KNOW?
lightbulbPython'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:
add(a, b)- This function should return the sum of two numbers.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 and .
- Print the result of subtracting from .
Make sure to run your main.py script and verify that the output is correct.