Tutorials Logic, IN info@tutorialslogic.com

Python Functions def, args, kwargs, return

Python Functions

Python functions model reusable behavior. They take inputs, perform a focused task, and return a result or intentional side effect.

This page is different from classes: functions are best for stateless actions; classes are best when state and behavior live together over time.

Reusable Behavior

A function turns repeated logic into a named unit that can be tested and reused. Good function names explain the task.

  • Use functions for repeated actions.
  • Keep one function focused.
  • Prefer return values over hidden global changes.

Parameters and Returns

Parameters describe what the function needs. Return values describe what the caller gets back. Clear boundaries make code easier to test.

  • Use keyword arguments for clarity.
  • Avoid mutable defaults.
  • Keep return types consistent.

Scope and Side Effects

Functions are easiest to reason about when they depend mostly on parameters. File writes, network calls, and database updates should be obvious from the function name or design.

  • Avoid accidental global state.
  • Separate calculations from I/O.
  • Raise meaningful exceptions for invalid input.

Argument Patterns

Python functions can accept required arguments, default arguments, extra positional arguments with *args, and extra keyword arguments with **kwargs.

Use the simplest argument shape that communicates the job. Flexible arguments are useful for wrappers and utilities, but they can make beginner code harder to inspect.

  • Required parameters make needed input obvious.
  • Default parameters are useful when one value is common.
  • *args collects extra positional values into a tuple.
  • **kwargs collects extra named values into a dictionary.

Default, args, and kwargs

Default, args, and kwargs
def build_profile(name, role="student", *skills, **details):
    profile = {
        "name": name,
        "role": role,
        "skills": list(skills),
        "details": details,
    }
    return profile

user = build_profile("Maya", "developer", "Python", "SQL", city="Pune")
print(user["skills"])
print(user["details"]["city"])
Output
['Python', 'SQL']
Pune

role has a default value, *skills collects extra skill names, and **details collects named extra data such as city.

Invoice Total Function

Invoice Total Function
def calculate_invoice_total(items, tax_rate=0.18):
    subtotal = sum(item["price"] * item["quantity"] for item in items)
    return round(subtotal + subtotal * tax_rate, 2)
Function design check

Can You Package Reusable Logic?

5 checks
  • Define focused functions with names that describe the action.
  • Use parameters for input and return values for reusable output.
  • Avoid mutable default arguments such as [] or {}.
  • Use *args and **kwargs only when flexible arguments are truly needed.
  • Keep printing, file access, and network work separate from pure calculations when possible.

Function Decisions

0 of 2 checked

Q1. Why should reusable functions usually return values instead of only printing?

Q2. What is a warning sign that a function does too much?

Function Design Traps

  • Printing instead of returning

    Return values from reusable functions, then print at the outer script level when needed.
  • Too many jobs in one function

    Split input, calculation, validation, and display when one function becomes hard to name.
  • Changing outside state silently

    Prefer inputs and return values unless mutation is the purpose of the function.

Try this next

Package One Reusable Task

0 of 3 completed

  1. Move a tax calculation into calculate_total(price, tax_rate).
  2. Write summarize_scores(scores) that returns count, highest, and average.
  3. Call the function with an empty list or zero value and decide what should happen.

Questions About Function Design

*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. You can use both: def func(*args, **kwargs). They allow functions to accept any number of arguments.

A decorator is a function that takes another function and extends its behavior. Applied with @decorator_name syntax. Common uses: @staticmethod, @classmethod, @property, @functools.lru_cache for memoization.

A function is defined at module level with def. A method is a function defined inside a class. Methods automatically receive the instance (self) or class (cls) as the first argument.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.