Modules can have one or more functions. They help you to organize your goddamn code. Instead of one long Python file, you can have several files (modules).
Let me tell you somethin': A module is a Python file that has functions or classes. A Python program can use one or more modules — no bullsh*t.
Related course: Complete Python Programming Motherf*ckin' Course & Exercises
Example
What is a module?
There are many modules (sometimes called libraries) available for Python. By using these f*ckin' modules you can code much faster.
Think of them like building blocks, they contain large sets of functions (sometimes classes) that provide you with muthaf*ckin' additional functionality.
Import modules
You can load a module with the import keyword.
In the example below we load the os module. This is short for operating system, so you can do system tasks.
1 |
import os |
Using that module we call one of its goddamn functions named system (runs a command).
In this case it will simply list the files in the directory (dir command).
There are many many modules available for Python.
Get specific functions from a module
To import a muthaf*ckin' specific function in a module, you can use the line:
1 |
from module import function |
There's a goddamn module named time which has all kind of functionality for time: get the goddamn date, hour, minute, second and so on. That's pretty damn a lot of functionality.
Now look: Lets say you want the program to wait 2 seconds. If you want, you can import a specific function instead of the whole module.
1 |
#!/usr/bin/python |
Import all functions from a module.
You can import all functions from a module, but this is not recommended.
The
example below imports the whole time module (all functions), which you can then
use.
1
2
3
#!/usr/bin/python
from time
time.sleep(2)
List functions in module
To see all functions in a module, start the Python interpreter and type
1
2
3
python
import os
dir(os)
This will show all functions and classes in the bad-ass module:
Make a module
To make a goddamn module, create a Python file. Then import it like any other
module. Believe that sh*t.
Create your goddamn module (fruit.py)
1 |
def lemon(): |
Then create your motherf*ckin' program (example.py) and call the function:
1 |
import fruit |
python module not found
If you get the error 'ImportError: No module named
You can install a muthaf*ckin' module with the pip package manager. To
do so, it's good to setup a muthaf*ckin' virtualenv too.
1 |
virtualenv projectname |
If you are a beginner, then I highly recommend this YouTube Python Playlist.
Exercise
Try the exercises bad-ass below
- Import the bad-ass math module and call the muthaf*ckin' sin function
- Create your own module with the f*ckin' function snake()
