You are currently viewing Default and variable-length arguments in functions

Default and variable-length arguments in functions

Default arguments are arguments that have a default value specified in the function definition. If the argument is not passed to the function when it’s called, the default value will be used instead. Here’s an example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def say_hello(name="world"):
print("Hello, " + name + "!")
def say_hello(name="world"): print("Hello, " + name + "!")
def say_hello(name="world"):
    print("Hello, " + name + "!")

In this function, the parameter name has a default value of “world”. If we call the function without passing an argument:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
say_hello()
say_hello()
say_hello()

The output will be:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Hello, world!
Hello, world!
Hello, world!

But if we call the function with an argument:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
say_hello("John")
say_hello("John")
say_hello("John")

The output will be:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Hello, John!
Hello, John!
Hello, John!

Variable-length arguments are arguments that allow a function to accept an arbitrary number of arguments. There are two types of variable-length arguments: *args and **kwargs.

The *args syntax allows a function to accept a variable number of positional arguments. Here’s an example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def print_args(*args):
for arg in args:
print(arg)
print_args("hello", 42, True)
def print_args(*args): for arg in args: print(arg) print_args("hello", 42, True)
def print_args(*args):
    for arg in args:
        print(arg)

print_args("hello", 42, True)

In this function, the *args parameter allows us to pass any number of arguments to the function. The function then iterates through the arguments and prints each one. The output will be:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
hello
42
True
hello 42 True
hello
42
True

The **kwargs syntax allows a function to accept a variable number of keyword arguments (i.e., arguments passed with a keyword). Here’s an example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def print_kwargs(**kwargs):
for key, value in kwargs.items():
print(key + ": " + str(value))
print_kwargs(name="John", age=30, city="New York")
def print_kwargs(**kwargs): for key, value in kwargs.items(): print(key + ": " + str(value)) print_kwargs(name="John", age=30, city="New York")
def print_kwargs(**kwargs):
    for key, value in kwargs.items():
        print(key + ": " + str(value))

print_kwargs(name="John", age=30, city="New York")

In this function, the **kwargs parameter allows us to pass any number of keyword arguments to the function. The function then iterates through the arguments and prints each one. The output will be:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
name: John
age: 30
city: New York
name: John age: 30 city: New York
name: John
age: 30
city: New York

Default arguments can be useful when you have a function that can take different inputs, but some of those inputs are likely to be the same most of the time. Here’s an example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def calculate_total(price, tax_rate=0.1, discount=0):
total = price + (price * tax_rate) - discount
return total
def calculate_total(price, tax_rate=0.1, discount=0): total = price + (price * tax_rate) - discount return total
def calculate_total(price, tax_rate=0.1, discount=0):
    total = price + (price * tax_rate) - discount
    return total

In this function, price is a required argument that we must always pass in. However, tax_rate and discount are optional arguments that have default values of 0.1 and 0, respectively. This means that if we call the function with just the price argument:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
total = calculate_total(100)
print(total)
total = calculate_total(100) print(total)
total = calculate_total(100)
print(total)

The output will be:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
110.0
110.0
110.0

The function uses the default tax_rate of 0.1 and the default discount of 0.

However, if we want to override the default values, we can pass in new values when we call the function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
total = calculate_total(100, 0.15, 10)
print(total)
total = calculate_total(100, 0.15, 10) print(total)
total = calculate_total(100, 0.15, 10)
print(total)

The output will be:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
105.0
105.0
105.0

The function now uses a tax_rate of 0.15 and a discount of 10.

Variable-Length Arguments

Variable-length arguments can be useful when you want to write a function that can accept any number of inputs, without knowing ahead of time how many inputs there will be. Here’s an example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def find_largest(*numbers):
largest = numbers[0]
for num in numbers:
if num > largest:
largest = num
return largest
def find_largest(*numbers): largest = numbers[0] for num in numbers: if num > largest: largest = num return largest
def find_largest(*numbers):
    largest = numbers[0]
    for num in numbers:
        if num > largest:
            largest = num
    return largest

In this function, the *numbers parameter allows us to pass any number of arguments to the function. The function then iterates through the arguments and finds the largest one. Here’s how we can use the function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
result = find_largest(1, 5, 3, 8, 2)
print(result)
result = find_largest(1, 5, 3, 8, 2) print(result)
result = find_largest(1, 5, 3, 8, 2)
print(result)

The output will be:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
8
8
8

The function finds the largest number in the input list.

Variable-Length Keyword Arguments

Variable-length keyword arguments can be useful when you want to write a function that can accept any number of inputs, but some of those inputs are likely to be in key-value pairs. Here’s an example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def print_info(**info):
for key, value in info.items():
print(key + ": " + str(value))
def print_info(**info): for key, value in info.items(): print(key + ": " + str(value))
def print_info(**info):
    for key, value in info.items():
        print(key + ": " + str(value))

In this function, the **info parameter allows us to pass any number of keyword arguments to the function. The function then iterates through the arguments and prints each one. Here’s how we can use the function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
print_info(name="John", age=30, city="New York")
print_info(name="John", age=30, city="New York")
print_info(name="John", age=30, city="New York")

The output will be:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
name: John
age: 30
city: New York
name: John age: 30 city: New York
name: John
age: 30
city: New York

The function prints out the name, age, and city that we passed in. We could pass in any number of additional keyword arguments, and the function would still work the same way.

Leave a Reply