Nearby lessons

64 of 108

Python - Function Arguments

What Are Function Arguments?

Arguments are the values we pass to a function when we call it.

They help the same function work with different inputs.

Types of Arguments

  • Positional arguments
  • Keyword arguments
  • Default arguments
  • Variable-length arguments

Positional and Keyword Arguments

Positional arguments are matched by order. Keyword arguments are matched by name.

def wish(name, msg):
    print("Hello", name, msg)

Default Arguments

Default arguments provide a fallback value if the caller does not pass one.

def wish(name="Guest"):
    print("Hello", name, "Good Morning")

Variable-Length Arguments

Use *args for many positional values and **kwargs for many keyword values.

def sum(*n):
    total = 0
    for value in n:
        total += value
    return total

Important Rules

  • Positional arguments must come before keyword arguments.
  • After a default argument, non-default arguments are not allowed.
  • *args is stored as a tuple.
  • **kwargs is stored as a dictionary.

Summary

Argument Type Meaning
PositionalMatched by order
KeywordMatched by name
DefaultUses fallback value
Variable-lengthAccepts many values

🧠 Test Your Knowledge

3 Questions

Progress: 0 / 3
Keep Going!Python - Return Statement