[last updated: 2021-08-08]
go to: Python home page
go to: Python: Programming Statements
-----
- Define a Function:
- Code to define a function starts with "def"
followed by the function name,
followed by "( )" that contain any parameters passed to the function,
followed by a colon ":"
- The statements that make up the body of the function follow, and must be indented from the "def" line
- A "return" statement or an un-indented line will mark the end of a function definition
Note: a return statement is good practice,
since if eg. you have a null function with nothing in it other than perhaps a comment,
it will fail with error if there's no return statement.
(same applies - according to my trials - if you only have file open & close statements in the function)
- For example:
- Using a Function:
- Using a function inside the program where it's defined:
- call a function with:
calcFunc()
- The function call must be executed After the function is defined in your program.
- Using a function in a different program (in the same directory):
(Note: These procedures worked in both python 2.7.15 and python 3.5.3)
Functions must be "imported" to use them in a different program:
Suppose you have defined a function, eg. func01
and it's defined (located) in eg. funcs.py
and you want to use this function in a different program, eg. main.py
- Put these lines into main.py:
- import funcs
then execute with:
funcs.func01()
- or:
import funcs as F1 (where 'F1' is your choice of name/tag)
then execute with:
F1.func01()
- or:
from funcs import func01 (only imports the func01 function from funcs)
then execute with:
func01()
one source recommended using: from .funcs import func01
but this failed with error something about "relative imports" and "parent not loaded"
- or:
from funcs import * (imports all functions defined in funcs)
then execute the same, with:
func01()
However: one note said this method failed with python 3.5.4...
- Using a function in a different program (in a different directory):
----------------------------------------------------------------
- Misc Notes to Edit:
- If sub.py is just a collection of functions that you've defined,
then you can import them and call them from main.py with this:
import sub Note: Do NOT include the .py of your sub.py
sub.func_to_call()
Confirmed
- If sub.py also contains statements,
then they will be executed (once) when you do the import
---------------------------------------------------------------
.
.
.
eof