Modules: Keep It Tidy
Imagine reading a 10,000-page book that had no chapters, no paragraphs, and no index. It would be impossible to find anything! The same goes for code. If you put all your code in one massive file, it becomes a nightmare to manage.
Just another Python file
A ModuleA file containing Python code (functions, variables, etc.) that can be imported into other files.
is literally just a .py file with some functions and variables inside it. That's it!
If you create a file called math_tricks.py and write some cool math functions in it, you have just created a module.
Borrowing code from other files
To use the functions from a module in your main program, you use the import keyword.
Once imported, you use a dot . to access the functions inside it.
# Import the math_tricks module import math_tricks # Use a function from that module using a dot result = math_tricks.add(5, 10) print(result)
math_tricks.py and bring all its code here.". means "look inside math_tricks and run the add function".Python's Built-in Modules
You don't always have to write your own modules. Python comes with a massive library of built-in modules that are ready to use immediately! They call this the "batteries included" philosophy.
import math- Advanced math functions (square roots, trigonometry, pi).import random- Generate random numbers, pick random items from a list.import datetime- Work with dates and times.
import random # Roll a 6-sided die! dice_roll = random.randint(1, 6) print("You rolled a:", dice_roll)
Think of Modules like Toolboxes.
You don't carry every single tool you own in your pockets at all times. That would be too heavy! (This is why Python doesn't load every function automatically).
Instead, if you are doing plumbing, you go to your truck and import plumbing_toolbox. If you are doing electricity, you import electrical_toolbox.
How Imports Work
Reinventing the Wheel
import random... done. π"Don't reinvent the wheel. Someone else probably already built the module!
Importing Tools
Try using Python's built-in random and math modules.
- Run the code to see what random number you get. Run it multiple times!
- Use
random.choice()to pick a random fruit from the list instead of a random number. - Import the
mathmodule at the top, and print outmath.pi.
Organizing Your Code β Done! π
- A Module is simply a `.py` file containing Python code.
- You use the import keyword to bring a module into your current file.
- Use the dot (.) to access functions inside a module, like
math.sqrt(). - Python has "batteries included". Modules like
randomandmathare pre-installed and ready to import. - Modules are like toolboxesβonly import the ones you need!