How to handle any number of inputs in Python functions

How Python handles flexible inputs (and why it matters for real-world code)

In partnership with

Whether you're just starting out or tightening up your Python skills, mastering functions is non-negotiable. This guide walks you through everything, basic def syntax, handling args and *kwargs, with clear examples and tips that will instantly level up your code quality.

Partner Messages

Learn AI in 5 minutes a day

This is the easiest way for a busy person wanting to learn AI in as little time as possible:

  1. Sign up for The Rundown AI newsletter

  2. They send you 5-minute email updates on the latest AI news and how to use it

  3. You learn how to become 2x more productive by leveraging AI

Start learning AI in 2025

Keeping up with AI is hard – we get it!

That’s why over 1M professionals read Superhuman AI to stay ahead.

  • Get daily AI news, tools, and tutorials

  • Learn new AI skills you can use at work in 3 mins a day

  • Become 10X more productive

Let’s talk about args and kwargs

If you're learning Python, one of the most valuable skills you can develop is writing flexible, reusable functions. A well-written function does more than organize your code. It makes your programs easier to maintain, easier to understand, and far more adaptable as your projects grow.

Two tools that often confuse new developers are args and kwargs. At first glance, they can seem cryptic. But they solve a very practical problem: how to write functions that accept a changing number of inputs.

When you use args, you’re telling Python to accept any number of positional arguments. These get bundled into a tuple you can loop through or process however you like. On the other hand, *kwargs collects any number of keyword arguments and stores them in a dictionary. That means your function can accept optional named inputs without needing to define them all in advance.

def demo_function(*args, **kwargs):
    print("Positional arguments (args):")
    for i, arg in enumerate(args):
        print(f"  arg[{i}] = {arg}")
    
    print("\nKeyword arguments (kwargs):")
    for key, value in kwargs.items():
        print(f"  {key} = {value}")

# Call the function with several positional and keyword arguments
demo_function(10, 20, 30, name="Alice", age=28, job="Engineer")

These features are especially useful when building tools that need to handle different types of user input or wrap around other functions. If you’ve ever written code that broke because you didn’t anticipate an extra input, args and kwargs are how you prevent that.

Rate this Newsletter

The team at Hackr.io aims to provide the best information possible. Please let us know how we're doing!

Login or Subscribe to participate in polls.