How to Call a Function in Python
PythonExecute functions with parentheses, pass arguments correctly, capture return values, and invoke functions by name when needed.
Use parentheses after a function name to execute it in Python. Define the function with def, then call it as name(). See the official tutorial for defining functions at docs.python.org.
Method 1: Call a function directly
Step 1: Define a function with def.
def greet():
print("Hello from a function")Step 2: Execute the function by adding parentheses to its name.
greet() # prints: Hello from a functionMethod 2: Call with arguments (positional, keyword, defaults, variable-length)
Step 1: Call with positional arguments in the order parameters are defined.
def full_name(fname, lname):
print(fname, lname)
full_name("Emil", "Refsnes")Step 2: Call with keyword arguments to specify parameters by name (order does not matter).
full_name(lname="Refsnes", fname="Emil")Step 3: Mix positional first, then keyword arguments; do not place positional arguments after keywords.
def cost(item, quantity, price):
print(f"{quantity} {item} cost ${quantity * price:.2f}")
cost("bananas", quantity=6, price=0.74) # OK
# cost(item="bananas", 6, 0.74) # SyntaxError: positional after keywordStep 4: Use default parameter values by omitting that argument in the call.
def origin(country="Norway"):
print("I am from", country)
origin() # uses default "Norway"
origin("India") # overrides defaultStep 5: Accept a variable number of positional arguments with *args.
def youngest(*kids):
print("The youngest child is", kids[2])
youngest("Emil", "Tobias", "Linus")Step 6: Accept a variable number of keyword arguments with **kwargs.
def show_last_name(**kid):
print("His last name is", kid["lname"])
show_last_name(fname="Tobias", lname="Refsnes")Step 7: Require positional-only arguments by placing / in the signature (Python 3.8+).
def echo(x, /):
print(x)
echo(3) # OK
# echo(x=3) # TypeError: positional-onlyStep 8: Require keyword-only arguments by placing * before them.
def scale(*, factor):
print(f"Scaling by {factor}")
scale(factor=3) # OK
# scale(3) # TypeError: keyword-onlyMethod 3: Capture and use a function’s return value
Step 1: Return a value with return inside the function.
def times5(x):
return 5 * xStep 2: Assign the return value to a variable.
result = times5(9)Step 3: Use the value in further code or print it.
print(result) # 45Method 4: Call a function by its name (string) safely
Prefer attribute lookup over eval. Use getattr to retrieve a function object by name, then call it. See the official getattr docs at docs.python.org.
Step 1: Import the module that contains the function.
import mathStep 2: Retrieve the function by name with getattr(module, "name").
func = getattr(math, "sqrt") # <built-in function sqrt>Step 3: Call the retrieved function like any other callable.
print(func(16)) # 4.0Step 4: Import a module by string with importlib.import_module when both module and function names are dynamic.
from importlib import import_module # docs: https://docs.python.org/3/library/importlib.html#importlib.import_module
module_name, func_name = "random", "randint"
mod = import_module(module_name)
print(getattr(mod, func_name)(1, 6))Step 5: Avoid eval/exec for calling by name.
- They execute arbitrary code, which introduces serious security risks.
- Attribute lookup is explicit, safer, and easier to test.
Method 5: Use a dispatch dictionary for user-selected actions
Map input strings to callables, then look up and call—this simplifies long if/elif chains and keeps the code maintainable.
Step 1: Build a dictionary of command names to functions.
def bw(img): ...
def sepia(img): ...
def pencil_sketch(img, mode): ...
# wrap different signatures if needed
def psg(img): return pencil_sketch(img, 1)
def psc(img): return pencil_sketch(img, 2)
EFFECTS = {
"bw": bw,
"sepia": sepia,
"psg": psg,
"psc": psc,
}Step 2: Retrieve the callable from the mapping and execute it.
effect = input("Effect: ").strip().lower()
img = ... # your image
func = EFFECTS.get(effect)
if func:
func(img)
else:
print("Please enter a valid effect name.")Step 3: Store partials or lambdas if you need to bind arguments ahead of time.
from functools import partial
EFFECTS = {
"psc": partial(pencil_sketch, mode=2),
# later: EFFECTS["psc"](img)
}Method 6: Call a function from another file (module)
Step 1: Import the module or the function you need.
# file: utils.py
def shout(msg):
print(msg.upper())
# file: app.py
import utils
from utils import shoutStep 2: Call using either the module attribute or the directly imported name.
# via module
utils.shout("hello")
# via direct import
shout("hello")Step 3: Keep module paths importable (current working directory or package on PYTHONPATH), so imports resolve reliably.
Quick checks and common errors
Step 1: Ensure the function is defined before it’s called at runtime.
# OK: bar is defined by the time foo() runs
def foo():
bar() # fine because bar is defined before this call executes
def bar():
print("bar")
foo()Step 2: Match the expected number of arguments or provide defaults.
def add(a, b): return a + b
# add(1) # TypeError: missing required positional argumentStep 3: Remember that calling a function requires parentheses; using the name alone refers to the function object.
def hello(): return "hi"
print(hello) # <function hello at ...>
print(hello()) # "hi"With these patterns you can call Python functions directly, pass the right kinds of arguments, capture results, and even invoke callables by name without unsafe code. Keep your interface clear, prefer explicit lookups over eval, and your function calls will stay simple and predictable.
Comments