Python Advanced #2 - Functions

This post will explain how to use functions in Python.  Basically, functions are written to avoid having to duplicate code in a program by allowing you to call a piece of code multiple times.  Additionally, once a function is written it can be used in other programs.

In the figure below, two functions have been written.  The functions are "sum_nums" and "avg_nums".  A function is defined by using def.  The "val1" and "val2" in the parentheses of the function are known as parameters.  We call the function from the main program by simply using the name of the function and providing the arguments.  In our example below, the arguments are "num1" and "num2".


Below is the output from the program.


In the example above, the function was placed inside of the program, however, if you are planning to use your functions in multiple programs, you may want to store them outside of your program and then import them.  To demonstrate this, a new function is created in the file multip_func.py.  This new file is created the same way you have created other programs, and it is shown below.


The coding to import and use this external function has been added to the original code and is shown below.



The results from the code are shown below.


You can also have multiple functions in a file.  To demonstrate this, we can add a division function to the file, multip_func.py (probably not named correctly now, but that's ok).  This is shown below.




We could import both functions separately, but since we want all functions in the file, we can use the following:

from multip_func import *

We also want to add an additional print statement at the bottom and call the function, div_nums.

This is shown below.


The results from the code are shown below.


Comments