Python Function Arguments

Arguments are values passed to a function when it is called. They allow functions to work with different data. Positional Arguments Arguments are assigned to parameters based on their position. Example Output: Keyword Arguments You can send arguments using parameter names. Example Output: Default Arguments A default value is used if no argument is provided. […]

2 mins read Lesson 13 of 43 30% through track

Arguments are values passed to a function when it is called. They allow functions to work with different data.

Positional Arguments

Arguments are assigned to parameters based on their position.

Example

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

greet("John", 25)

Output:

John 25

Keyword Arguments

You can send arguments using parameter names.

Example

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

greet(age=25, name="John")

Output:

John 25

Default Arguments

A default value is used if no argument is provided.

Example

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

greet()
greet("John")

Output:

Hello Guest
Hello John

Arbitrary Arguments (*args)

If you do not know how many arguments will be passed, use *args.

Syntax

def function_name(*args):
    pass

Example

def students(*names):
    print(names)

students("John", "Alice", "Bob")

Output:

('John', 'Alice', 'Bob')

Accessing *args Values

Example

def students(*names):
    print(names[0])

students("John", "Alice", "Bob")

Output:

John

Arbitrary Keyword Arguments (**kwargs)

If you do not know how many keyword arguments will be passed, use **kwargs.

Syntax

def function_name(**kwargs):
    pass

Example

def student(**data):
    print(data)

student(name="John", age=20)

Output:

{'name': 'John', 'age': 20}

Accessing **kwargs Values

Example

def student(**data):
    print(data["name"])

student(name="John", age=20)

Output:

John

Combining Different Argument Types

Example

def details(name, age=18):
    print(name, age)

details("John")
details("Alice", 25)

Output:

John 18
Alice 25

Summary

  • Positional arguments are matched by position.
  • Keyword arguments are matched by parameter name.
  • Default arguments provide fallback values.
  • *args allows multiple positional arguments.
  • **kwargs allows multiple keyword arguments.
  • Different argument types can be used together in a function.