Introduction and Overview

Welcome back, explorers! Today, we're delving into optional and variable-length arguments in Python. Just as a space mission requires essential tools and optional gear depending on the mission, Python functions involve required and optional arguments. So, let's embark on this mission!

Taking Off: Exploring Optional Arguments

Firstly, let's tackle optional arguments! Optional arguments are parameters that a function can accept but don't necessarily need to function. They have a default value, which the function uses if no argument is provided during the function call.

def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Luke", "May the Force be with you") # Prints: "May the Force be with you, Luke!"
greet("Han") # Prints: "Hello, Han!"

In this function, name is essential, whereas greeting is optional, with "Hello" as the default. The optional argument depends on whether or not it's provided during the function call.

Igniting the Rocket: Using Optional Arguments

Next, we will look at calling functions with optional arguments. You have the flexibility to specify arguments via their position or by their name:

greet("Luke", greeting="May the Force be with you") # Prints: "May the Force be with you, Luke!"
greet(name="Han") # Prints: "Hello, Han!"

These function invocations do the same thing — they just indicate arguments differently. However, remember not to provide more arguments than those listed in the function or forget the required ones — if so, Python will raise an Error!

Thrusters on Full: A Voyage to Variable-length Arguments

Are you ready for variable-length arguments? In Python, a function can handle an uncertain number of arguments using an asterisk (*) in front of an argument's name.

def launch_payload(*payload):
    print("Launching payload into space:")
    for item in payload:
        print(f"- {item}")

launch_payload("Satellite", "Rover", "Radio Beacon")
"""
Prints:
Launching payload into space:
- Satellite
- Rover
- Radio Beacon
"""

Here, the function launch_payload() accepts any number of arguments, bundled into a tuple named payload. We then print each item in payload.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal