Lesson

Python Functions

10 min reading
Free Course

Python Functions: Parameters, Return Values, and *args/**kwargs

A Python function is a reusable named block of code defined with the def keyword. Functions split large scripts into small, testable units that accept inputs through parameters and send outputs back with return.

Keeping each function focused on one clear job makes your code easy to test, reuse, and read months later.

Defining Functions with Defaults and Type Hints

Parameters can define default values for optional arguments, and optional type hints document expected types for editors and linters.

def apply_discount(price: float, percent: float = 10.0) -> float:
    """Calculate final price after applying a percentage discount."""
    discount = price * (percent / 100)
    return round(price - discount, 2)

print(apply_discount(100))           # 90.0 (uses default 10%)
print(apply_discount(100, percent=25))  # 75.0 (keyword argument)

Flexible Inputs with *args and **kwargs

Use *args to accept any number of positional arguments as a tuple, and **kwargs to accept arbitrary keyword arguments as a dictionary.

def log_event(event_name: str, *tags: str, **details: object) -> None:
    print(event_name, tags, details)

log_event("signup", "web", "promo", user_id=42, plan="pro")

Common Mistakes to Avoid

  • Using mutable default arguments like items=[]: Python creates default objects once when defining the function, so mutated defaults leak across calls; use items: list | None = None instead.
  • Using print() instead of return: Functions without return give back None, which breaks callers expecting a value.
  • Putting positional arguments after keyword arguments: apply_discount(percent=20, 100) raises a SyntaxError.

Frequently Asked Questions

What happens if a function has no return statement?

Python automatically returns None when execution reaches the end of the function body.

What is the difference between a parameter and an argument?

A parameter is the variable name in the def signature (price), while an argument is the actual value passed during the call (100).

Do Python type hints enforce types at runtime?

No. Python ignores type hints at runtime, though tools like mypy, pyright, and VS Code check them statically before you run the code.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
Lesson Recap Quiz Available

Test Your Knowledge

You've completed this section! Take a quick 5-question quiz to check your understanding.

Python Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum