Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • distinguish positional and keyword arguments
  • use default arguments correctly
  • understand *args and **kwargs at introductory level

Positional arguments

def introduce(name, age):
    print(name, age)

introduce("Riya", 19)
Order matters.

Keyword arguments

introduce(age=19, name="Riya")
Order can change because names are specified.

Default arguments

def greet(name, msg="Hello"):
    print(msg, name)

greet("Asha")
greet("Asha", "Hi")

Variable-length positional arguments

def add_all(*nums):
    total = 0
    for x in nums:
        total += x
    return total

Variable-length keyword arguments

def show_info(**data):
    print(data)

Common rules

  • positional arguments must come before keyword arguments in function call
  • default arguments should be placed after required ones in definition
Wrong:
# def f(x=1, y):   # invalid

Exam hints and traps

  • missing required argument raises TypeError
  • too many arguments also raise TypeError
  • default value is used only when caller does not supply that argument

Quick practice

  1. Write function with default argument country="India".
  2. Call a function once with positional and once with keyword style.
  3. Explain what *nums collects.