Python Function Argument

http‮s‬://www.theitroad.com

In Python, there are two types of function arguments: positional arguments and keyword arguments.

Positional arguments are passed to the function in the order they are listed in the function definition. For example:

def greet(name, greeting):
    print(greeting + ', ' + name + '!')
    
greet('Alice', 'Hello')  # Output: Hello, Alice!

In this example, the function greet takes two positional arguments: name and greeting. When the function is called with the arguments 'Alice' and 'Hello', the output is 'Hello, Alice!'.

Keyword arguments are passed to the function using the name of the parameter. This allows you to pass arguments to a function in any order, as long as you specify the name of the parameter. For example:

def greet(name, greeting):
    print(greeting + ', ' + name + '!')
    
greet(greeting='Hello', name='Alice')  # Output: Hello, Alice!

In this example, the function greet is called with two keyword arguments: greeting='Hello' and name='Alice'. The order of the arguments does not matter, because they are specified by name.

Functions can also have default parameter values, which are used if a value is not provided for that parameter. For example:

def greet(name, greeting='Hello'):
    print(greeting + ', ' + name + '!')
    
greet('Alice')  # Output: Hello, Alice!

In this example, the function greet has a default value of 'Hello' for the greeting parameter. If the function is called with only one argument, the default value is used. The output of the function call is 'Hello, Alice!'.

Functions can also take a variable number of arguments using the *args and **kwargs syntax. *args allows you to pass a variable number of positional arguments to a function, and **kwargs allows you to pass a variable number of keyword arguments. Here's an example:

def print_arguments(*args, **kwargs):
    print('Positional arguments:', args)
    print('Keyword arguments:', kwargs)
    
print_arguments(1, 2, 3, name='Alice', age=30)

In this example, the function print_arguments takes a variable number of arguments using *args and **kwargs. When the function is called with the arguments 1, 2, and 3, as well as the keyword arguments name='Alice' and age=30, the output is:

Positional arguments: (1, 2, 3)
Keyword arguments: {'name': 'Alice', 'age': 30}