Here’s a hard truth: if you’re not using functions in your code, you’re fighting against the tooling that the language provides to you to help you follow best practices.

A good software engineer is, in part, gauged on their ability to write clean, maintainable, and reusable code. The way Python is written allows us to write logic in functions, and it’s important that every developer understands how they work.

They’re important because they:

  • Add modularity by breaking down larger problems into smaller chunks

  • Enhance reusability and improves readability

  • Encapsulate logic for better clarity

  • Make testing and debugging easier

The Basics of a Python Function

Let’s start out with a simple example:

def say_hello():
    print("Hello, world!")

say_hello()  # Output: Hello, world!

Functions are defined by the reserved word def, followed by the name of the function (in this case, say_hello).

In the parenthesis, you’ll pass in your arguments (there’s none in this example; more on this below).

Everything that is indented under def is part of the function. In this case, it’s just the print statement, but it’s very normal for functions to go much longer.

The last line is the function call - this is what makes the function run the code that’s indented.

» Side note: we won’t dive into scope here, as this can be quite lengthy. Understanding scope is important to functions. RealPython has a solid rundown on what scope is.

Real-World Example: Working with Dates

Python's datetime library shows excellent function design. By importing it, you can access functions like datetime.date.today() without understanding the complex internal implementation.

Let’s say we were to write a few functions

import datetime

# Get the current date 
def todays_date(): 
    now = datetime.date.today()
    print("Current date:", now)

# Get yesterday's date
def yesterday_date():
    yesterday = datetime.date.today() -datetime.timedelta(days=1)
    print("Yesterday's date:", yesterday)

# Get tomorrow's date
def tomorrow_date():
    tomorrow = datetime.date.today() + datetime.timedelta(days=1)
    print("Tomorrow's date:", tomorrow)

# Call the functions
todays_date()
yesterday_date()
tomorrow_date()

These functions work, but they're rigid. For example, what if we want any date relative to today? This is where arguments come into play.

Making Functions Flexible with Arguments

Diving a bit deeper into functions, we can force them to be more flexible by leveraging parameters, positional arguments, and keyword arguments.

Parameters vs Arguments: A parameter is defined in the function signature (name below), while an argument is the actual value passed when calling it ("Jane"):

def greet(name):  # ← 'name' is a parameter
    print(f"Hello, {name}!")

greet("Jane")     # ← "Jane Doe" is an argument

Positional vs Keyword Arguments: Positional arguments are matched by order, while keyword arguments are matched by name:

def greet(name, age):
    print(f"Hello {name}, you are {age} years old.")

greet("Jane", 30)           # Positional - order matters
greet(age=30, name="Jane")  # Keyword - order doesn't matter

Handling Variable Numbers of Arguments: When you don't know how many arguments will be passed, use these special symbols for your parameters:

*args collects extra positional arguments as a tuple (short for “arguments”):

def add_all(*args):
    return sum(args)

print(add_all(2, 4, 6))   # Output: 12

**kwargs collects keyword arguments as a dictionary (short for “keyword arguments”):

def print_details(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_details(name="Jane", age=30, role="Developer")

# name: Jane
# age: 30
# role: Developer

Key Takeaways

Functions are Python's backbone for modular, reusable code. Remember: parameters are what you define, arguments are what you pass.

Use positional arguments when order is logical, keyword arguments for clarity, and *args/**kwargs to pass in a variable number of arguments.

Pro tip: Use lambda functions for simple one-line transformations to keep your code concise.

Happy coding!

📧 Join the Python Snacks Newsletter! 🐍

Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:

  1. Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.

  2. Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.

  3. Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.

You can unsubscribe at any time.

Interested in starting a newsletter or a blog?

Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.

If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.

This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.

Reply

or to participate

Keep Reading

No posts found