Python Basics
Python Modules
Python modules
Python Modules
Consider a module to be the same as a code library. A file containing a set of functions you want to include in your application.
Create a Module
To create a module just save the code you want in a file with the file extension .py:
# Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
import mymodule
mymodule.greeting("Jonathan")
Variables in Module
The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):
# In mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
# In main file
import mymodule
a = mymodule.person1["age"]
print(a) # 36
Built-in Modules
Python has several built-in modules that you can import whenever you like:
import platform
x = platform.system()
print(x) # Linux, Windows, etc.