A function is simply a routine that can be called over and over and always performs the same function. For example if we had a function called squared that simply took a number and timed it by itself, we would have a function in python that looked like this:
s = ""
s = s*s
Then in your code you can reference that function by having a statement like:
num = square(5)
THe output of the above code would be 25, because you are passing the number 5 to the square function, which times it by itself and returns the value. This value is assigned to num and printed.
A module is basically a file that contains a series of predefined functions. Before you can add that module you would need to import it into your program as give that import a name so that you can reference these functions.
For example to import the sys module (and the functions it contains) you can type import sys
. This will now make any functions within the sys module available to your program. To use a function in the sys module you must reference it by its name like this sys.dir()
because the dir function is part of the sys module.
To make your own module, simply create a text file and save the functions you created into this text file and save it as a .py file. For example mymodule.py. To import that module so you can use it in other programs simply type import mymodule
and then you can reference the functions in there.