Functions are the building blocks of Python programming. They let you organize your code, reduce repetition, and make your programs more readable and reusable. Whether you’re writing small scripts or large applications, mastering functions is essential for clean, professional Python code.

In this tutorial, we’ll cover everything you need to know about defining and calling functions in Python. From the basics of def and parameters to advanced features like *args, **kwargs, positional-only parameters, lambdas, and docstrings—you’ll learn step by step with examples.

Method 1 — Create and Call a Basic Function

A Python function starts with the def keyword, followed by its name, parentheses for parameters, a colon, and an indented block of code.

def greet():
    print("Hello from a function!")

Call it by writing its name with parentheses:

greet()

✅ Key rule: Define first, call after—Python runs top to bottom, so functions must exist before you use them.

Method 2 — Add Parameters and Defaults

Functions can take input values called parameters.

def full_name(first, last):
    print(first + " " + last)

full_name("Ada", "Lovelace")

You can also set default values:

def hello(name="World"):
    print(f"Hello, {name}!")

hello()          # Hello, World!
hello("Python")  # Hello, Python!

Defaults make functions flexible and backward-compatible.See default arguments in the official tutorial.

READ 👉  How to Remove Items from a List in Python: The Complete Guide

Method 3 — Return Values

Instead of just printing, functions can return results with return:

def area(w, h):
    return w * h

a = area(3, 4)
print(a)  # 12

Functions can also return multiple values (as tuples):

def point():
    return 10, 20

x, y = point()

Details of the return statement are covered in the language reference.

Method 4 — Accept a Variable Number of Arguments

Sometimes you don’t know how many arguments will be passed. Python handles this with *args and **kwargs:

# Collect multiple positional arguments
def total(*args):
    return sum(args)

print(total(1, 2, 3))  # 6
# Collect keyword arguments
def report(**kwargs):
    for k, v in kwargs.items():
        print(k, "=", v)

report(name="Keyboard", price=19.99)

See “Arbitrary argument lists” in the official tutorial.

Method 5 — Control How Callers Pass Arguments

Python lets you enforce argument styles for clarity:

  • Positional-only parameters (with /):
def echo(x, /):
    print(x)

echo(3)       # OK
# echo(x=3)   # ❌ TypeError
  • Keyword-only parameters (with *):
def scale(value, *, factor=2):
    return value * factor

print(scale(10, factor=3))  # 30

This avoids misuse and makes APIs more intuitive.See “Special parameters” in the official tutorial.

Method 6 — Document and Organize Your Function

Write docstrings to describe your function’s purpose, parameters, and return values:

def hypotenuse(a, b):
    """Compute the length of the hypotenuse from legs a and b."""
    return (a**2 + b**2) ** 0.5

Also, use the if __name__ == "__main__": pattern to keep scripts import-safe:

def main():
    print(hypotenuse(3, 4))

if __name__ == "__main__":
    main()

Docstring conventions are defined in PEP 257, and the __main__ pattern is covered in the docs on executing modules as scripts.

Method 7 — Use a Lambda for Simple One-Liners

For quick, small functions, Python supports lambda expressions (anonymous one-liners):

double = lambda x: x * 2
print(double(5))  # 10

But prefer def for readability, docstrings, and reusability:

def double_def(x):
    return x * 2

Lambda syntax is specified in the language reference.

Method 8 — Place Definitions Where They’ll Be Executed

Since Python executes top-to-bottom, functions must be defined before they are called:

def hello():
    print("Hello")

hello()

Defining a function after calling it will raise a NameError.

You can also define nested helper functions inside another function:

def outer():
    def inner():
        return "scoped helper"
    return inner()

Quick Tips for Writing Better Functions

  • Parameters are names in the definition; arguments are values you pass.
  • Use pass as a placeholder when drafting functions.
  • Keep functions small and focused—easier to test and reuse.
  • Always use descriptive names and clear docstrings.
READ 👉  Grist – The Smart Spreadsheet for Managing Complex Data

Conclusion

Functions are at the heart of Python programming. By starting with simple definitions and gradually adding parameters, defaults, return values, flexible arguments, and documentation, you’ll develop clean, reusable, and professional code.

As your projects grow, these practices—along with *args, **kwargs, and pipelines of well-documented functions—will save you time and make your code more maintainable.

With Python’s function tools, you’re not just writing code—you’re designing APIs that are easy to read, use, and extend.

Did you enjoy this article? Feel free to share it on social media and subscribe to our newsletter so you never miss a post!

And if you'd like to go a step further in supporting us, you can treat us to a virtual coffee ☕️. Thank you for your support ❤️!
Buy Me a Coffee

Categorized in: