
In Python, def is a reserved keyword that is used to define a function. In fact, "def" is short for define.
A function contains markup that can be used one or more times in a script. In this example, a function named "Hello" is defined that will simply print the text "Hello World".
AVOID TROUBLE
The function must be defined before the function is called in the script.
#!/usr/bin/python
def Hello():
return "Hello World"
print(Hello())
In this example, running the Python script should print "Hello World".
~]$ python testing.py
Hello World
Passing in values
Values are commonly passed into a function. In this example, value "Hello World" is passed into the Hello function and the value is returned.
#!/usr/bin/python
def Hello(greeting):
return greeting
print(Hello("Hello World"))
In this example, running the Python script should print "Hello World".
~]$ python testing.py
Hello World
Or like this.
#!/usr/bin/python
def Hello(greeting):
return greeting
result = Hello("Hello World")
print(result)
Calling functions from another Python script
Often, shared functions are created in a "master" Python script, so that "child" Python scripts can use the shared functions.
Let's say functions.py contains the following.
#!/usr/bin/python
def Hello(greeting):
return greeting
Here is how you could call functions.py from another Python script, such as testing.py. In this example, every function in functions.py will be made available in the testing.py script.
AVOID TROUBLE
The "master" Python script being imported will need to reside in one of the sys.path directories.
#!/usr/bin/python
from functions import *
result = Hello("Hello World")
print(result)
Or, if you want to limit the scope of the functions being imported, you can import specific functions.
#!/usr/bin/python
from functions import Hello
result = Hello("Hello World")
print(result)
Renaming (as)
The as keyword can be used to rename a module. In this example, module is renamed to abc.
import module as abc
abc.foo("John Doe")
Importing part of a module (from)
Let's say module.py contains two subroutines, hello and world.
#!/usr/bin/python3
def foo(name):
print("Hello " + name)
def bar(name):
print(f"Hello {name}")
The from keyword can be used to only use one of the subroutines in module.py (foo in this example).
from module import foo
print("John Doe")
If the Python script that contains the function you want to include is not in your sys path, one option is to include the path like this.
import sys
sys.path.append("/path/to/directory")
Did you find this article helpful?
If so, consider buying me a coffee over at