Here is a sample program that imports a user module which contains functions
Code:
'''
Main_program.py
demonstrates how to import and call functions from another module
'''
import CallingFunctions
a_list = [1,2,3,4,5,6,7,8,9,10]
print CallingFunctions.func1(a_list)
print CallingFunctions.func5(a_list)
print CallingFunctions.func8(a_list)
The module that is imported is here
Code:
'''
Callingfunctions.py
imported into another program giving it access to the functions
'''
def func1(inputs=None):
x = sum(inputs)
return "sum some numbers: ", x
'''
more functions
'''
def func5(inputs=None):
x_sq = 0
for x in inputs:
x_sq += x**2
return "sum of squares: ", x_sq
'''
more functions
'''
def func8(inputs=None):
return "hello from 8: ", inputs
'''
more functions
'''
if __name__ == "__main__":
a_list = [1,2,3,4,5,6,7,8,9,10]
inputs = "test inputs"
a_dict = {1:[func1([1,2,3]) ],
5:[func5([1,2,3])],
8:[func8("inputs to 8")]}
needed = [1,5,8]
for akey in needed:
if akey in a_list:
action = a_dict[akey]
print "\naction: ", action
if the two *.py files are located within the same directory, you can import the CallingFunctions module and use its functions from the Main_program. In this manner you can create "helper" modules that can be used by other programs. you should also note, that for testing purposes, the CallingFunctions can be run in standalone mode with the addition of the code block denoted by the "if" statement towards the end
Bookmarks