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
def greet():
print("Hello from a function")
greet() # prints: Hello from a function
Join readers who trust AllThings.How
Add us as a preferred source on Google so our practical guides show up first next time you search.
Add to Google Preferences →Method 2: Call with arguments (positional, keyword, defaults, variable-length)
def full_name(fname, lname):
print(fname, lname)
full_name("Emil", "Refsnes")
full_name(lname="Refsnes", fname="Emil")
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 keyword
def origin(country="Norway"):
print("I am from", country)
origin() # uses default "Norway"
origin("India") # overrides default
def youngest(*kids):
print("The youngest child is", kids[2])
youngest("Emil", "Tobias", "Linus")
def show_last_name(**kid):
print("His last name is", kid["lname"])
show_last_name(fname="Tobias", lname="Refsnes")
def echo(x, /):
print(x)
echo(3) # OK
# echo(x=3) # TypeError: positional-only
def scale(*, factor):
print(f"Scaling by {factor}")
scale(factor=3) # OK
# scale(3) # TypeError: keyword-only
Method 3: Capture and use a function’s return value
def times5(x):
return 5 * x
result = times5(9)
print(result) # 45
Method 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.
import math
func = getattr(math, "sqrt") # <built-in function sqrt>
print(func(16)) # 4.0
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))
- 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.
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,
}
effect = input("Effect: ").strip().lower()
img = ... # your image
func = EFFECTS.get(effect)
if func:
func(img)
else:
print("Please enter a valid effect name.")
from functools import partial
EFFECTS = {
"psc": partial(pencil_sketch, mode=2),
# later: EFFECTS["psc"](img)
}
Method 6: Call a function from another file (module)
# file: utils.py
def shout(msg):
print(msg.upper())
# file: app.py
import utils
from utils import shout
# via module
utils.shout("hello")
# via direct import
shout("hello")
PYTHONPATH), so imports resolve reliably.Quick checks and common errors
# 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()
def add(a, b): return a + b
# add(1) # TypeError: missing required positional argument
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.






