Tuesday, 17 January 2023

Parameter and Arguments

In Python, functions are defined using the def keyword, followed by the function name and any parameters that it takes. These parameters are used to accept input values or data when the function is called. Understanding the difference between parameters and arguments in Python functions is important for writing correct and efficient code.

A parameter is a variable that is defined in the function definition. It is used to accept input values or data when the function is called. For example, in the following function definition, name and age are parameters:

def greet(name, age):
  """This function greets the person passed in as a parameter"""
  print("Hello, " + name + ". You are " + str(age) + " years old.")

An argument, on the other hand, is a value that is passed to the function when it is called. These values are assigned to the corresponding parameters in the function definition. For example, in the following function call, "John" and 25 are the arguments:

greet("John", 25)

In this example, the value of "John" is assigned to the name parameter, and the value of 25 is assigned to the age parameter.

You can also provide default values for the parameters, so that the function can be called without passing any arguments. For example, in the following function definition, the parameter power has a default value of 2:

def raise_to_power(x, power=2):
    """This function raises x to the power of power"""
    return x**power
 
print(raise_to_power(3))  # 3^2 = 9

You can also use *args and **kwargs to accept a variable number of arguments. *args allows you to pass a variable number of non-keyword arguments to a function, while **kwargs allows you to pass a variable number of keyword arguments.

def print_args(*args):
    """This function prints all the arguments passed to it"""
    for arg in args:
        print(arg)
 
print_args(1, 2, 3)
def print_kwargs(**kwargs):
    """This function prints all keyword arguments passed to it"""
    for key, value in kwargs.items():
        print(key + ": " + value)
 
print_kwargs(name="John", age=25)

In summary, when defining a function in Python, you specify the parameters that the function takes. When calling a function, you provide the corresponding arguments, which are then assigned to the parameters in the function definition. Understanding the difference between parameters and arguments is important for writing correct and efficient code.

In addition, you can also define default values for the function's parameters, so that the function can be called without passing any arguments. Also, you can use *args and **kwargs to accept a variable number of arguments.

 


No comments:

Post a Comment