Sobes.tech
Junior — Middle

What methods are available in Python for processing and passing arguments?

sobes.tech AI

Answer from AI

In Python, function arguments can be passed in several ways:

  1. Positional arguments — passed in the order in which the function parameters are declared.

  2. Named arguments — when calling a function, you can explicitly specify the parameter name, for example func(name="Alice"), which improves readability.

  3. Default arguments — function parameters can have default values, which are used if the argument is not provided.

  4. Arbitrary number of positional arguments (*args) — allows passing any number of positional arguments, which inside the function are accessible as a tuple.

  5. Arbitrary number of named arguments (**kwargs) — allows passing any number of named arguments, which inside the function are accessible as a dictionary.

Example:

def example(a, b=2, *args, **kwargs):
    print(f'a={a}, b={b}')
    print(f'args={args}')
    print(f'kwargs={kwargs}')

example(1, 3, 4, 5, x=10, y=20)

Output:

a=1, b=3
args=(4, 5)
kwargs={'x': 10, 'y': 20}