I'm having trouble creating my own module. I would like an example with a step by step of the steps to create a module so I can identify where I am going wrong.
I'm having trouble creating my own module. I would like an example with a step by step of the steps to create a module so I can identify where I am going wrong.
You seem to be confused about using direct import in the vs interpreter to run a .py
file with imports inside it. Without the code it's hard to understand where you're going wrong, but I'll start from the point where you read the python module documentation and you do not understand.
In the tutorial of the site he is using direct the interpreter. There, everything it imports will be available to be used in the next and only the interpreter's commands.
However, I understand that you want to import and run in a separate file. Using the example from own documentation , you can check here what would be a python application using module.
Explaining the code, the fibo.py
file provides the functions for calculating the fibonacci sequence that the main.py
file (shown below) will use:
# Fibonacci numbers module
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
File main.py
will be used as the main file, to start your application in python, importing the module you need:
from fibo import fib2
print(fib2(100))
See that the file name ( fibo
) is the name of the module itself.
Whereas you want to put your routines into a separate file. For example you have the media()
routine in your program:
def media(a,b):
return (a+b)/2.0
print(media(4,2))
Then you put in a separate file, "modulos.py" and edit your main program to:
from modulos import media
print(media(4,2))
Wishing to add more functions to "modulos.py", just do it:
def media(a,b):
return (a+b)/2.0
def maior(a,b):
return a if a>b else b
And then edit your program to load the functions you need:
from modulos import media, maior
Or load all available functions within it:
from modulos import *
Of course, this is a simple example of modules with all the files being in the same directory.