Function Arguments

Python tutorial · PySpark.in

Function Arguments

Function arguments are the actual values supplied to a function at the time of its execution. They enable a function to operate on different data values without modifying the function definition. Arguments provide flexibility and reusability to function

Need for Function Arguments

TYPES OF FUNCTION ARGUMENTS IN PYTHON

Python supports four main types of function arguments:

  1. Positional Arguments
  2. Keyword Arguments
  3. Default Arguments
  4. Variable-Length Arguments

POSITIONAL ARGUMENTS

Positional arguments are arguments that are passed to a function according to the position of parameters defined in the function. The order of arguments is significant in this type.

Characteristics

Example

```

def subtract(a, b):

return a - b

result = subtract(10, 5)

print(result)

```

Understanding the Example

Advantages

Limitations

Keyword arguments are arguments that are passed to a function using the parameter names, allowing values to be supplied in any order.

Characteristics

Example

```

def student(name, age):

print(name, age)

student(age=30, name="Rohan")

```

Understanding the Example

Advantages

Limitations

DEFAULT ARGUMENTS

A default argument is a parameter that assumes a predefined value if no corresponding argument is provided during function call. Default values are assigned at the time of function definition.

Characteristics

Example

```

def greet(name="Student"):

print("Hello", name)

greet()

greet("Megha")

```

Understanding the Example

Advantages

Limitations

VARIABLE-LENGTH ARGUMENTS

Variable-length arguments allow a function to accept any number of arguments, making the function more flexible.

Types of Variable-Length Arguments

  1. Non-keyword variable-length arguments (*args)
  2. Keyword variable-length arguments (**kwargs)

1. *args (Non-keyword Variable-Length Arguments)

*args allows multiple arguments to be passed to a function, which are internally stored as a tuple.

Example

```

def total(*numbers):

sum = 0

for i in numbers:

sum += i

return sum

print(total(1, 2, 3, 4))

```

2. **kwargs (Keyword Variable-Length Arguments)

**kwargs allows a function to accept any number of keyword arguments, which are stored as a dictionary.

Example

```

def details(**data):

for key, value in data.items():

print(key, value)

details(name="Rohan", age=20, course="Msc")

```

Advantages

Limitations


More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges