Learning Python

17. Modules

17.1. Using a module

Create a file called mymodule.py with the following

def greeting(name):
    print("Hello, " + name)

In our main program we can import the module and can call the function defined in the module.

import mymodule

def main():
    mymodule.greeting("John")

17.2. Using variable in modules

If we extent mymodule.py with the following

person = {
  "name": "John",
  "age": 42,
  "country": "Ireland"
}

We can now access the variable person and use age defined within person

import mymodule

def main():
    age = mymodule.person["age"]
    print(age)

Output:

42

17.3. Import from a module

You can also import a certain section from a module

from mymodule import person

def main():
    print(person["age"])

17.4. Rename a module

We can rename a module during import

import mymodule as abc

def main():
    age = abc.person["age"]
    print(age)

17.5. Built-in modules

import platform

def main():
    x = platform.system()
    print(x)
import platform

def main():
    x = dir(platform)
    print(x)