Cyberithub

9 Effective Ways to Pass Parameters to Python Functions

Advertisements

In this article, we will discuss about 9 effective ways to pass parameters to Python Functions. Like many programming languages, Python functions can take data as parameters and runs a block of code to perform a specific task. This code can be reused in multiple places by calling the function. There are several ways to pass parameters to Python functions. We will see all those ways in below section with the help of best examples. More on Python Functions.

9 Effective Ways to Pass Parameters to Python Functions

Effective Ways to Pass Parameters to Python Functions

There are certain ways in which which arguments to a function can be passed. Select a proper way based on the requirement and need.

  • Positional arguments(which need to be in the same order the parameters were written).
  • Keyword arguments(where each argument consists of a variable name and a value).
  • Lists and Dictionaries of values.

1. Positional argument

The order in which arguments are passed matters. Function when called matches the order in which parameter value is passed. It will throw error if value are not passed in order.

Program

def vehicle(name, model):
  print(f"I Own {name.title()}")
  print(f"{name.title()}'s Model is {model}")

vehicle('Swift', 'VXI')

Output

I Own Swift
Swift's Model is VXI

2. Keyword argument

The argument passed is name-value pair. The order in which arguments are passed doesn't really matter. But the total number of arguments should be equivalent to what has been defined as function's parameter. In below example, we have changed the order of values passed. Output remains the same.

Program

def vehicle(model, name):
  print(f"I Own {name.title()}")
  print(f"{name.title()}'s Model is {model}")

vehicle(name='Swift', model='VXI')

Output

I Own Swift
Swift's Model is VXI

3. Default Values

We can always pass default value to a parameter. In such case, if user doesn't provide the parameter value during function call, default value will be assigned to the variable.

Program

def vehicle(model, name='car'):
  print(f"I Own a {name.title()}")
  print(f"{name.title()}'s Model is {model}\n")

vehicle(model='VXI')    #uses default name value
vehicle(name='Swift', model='eco')

Output

I Own a Car
Car's Model is VXI

I Own a Swift
Swift's Model is eco

4. Optional argument

There comes a need where we want to make few argument optional. We may or may not pass the value of those variable. So keep those arguments as optional.

Program

def name(first, last, middle=''):
  full_name = f"{first} {middle} {last}"
  return full_name

data = name('Adam', 'Grook')
data1 = name('Saik', 'Ali', 'Grook')
print(data,"\n",data1)

Output

Adam  Grook
Saik Grook Ali

5. Returning a dictionary

Function in python can return any type of data like dictionary, list, tuple and so on.

Program

def name(first, last, middle=''):
  full_name = {'first_name': first, 'middle_name': middle, 'last_name': last}
  return full_name

data = name('Adam', 'Grook')
data1 = name('Saik', 'Grook', 'Ali')
print(data,"\n",data1)

Output

{'first_name': 'Adam', 'middle_name': '', 'last_name': 'Grook'}
{'first_name': 'Saik', 'middle_name': 'Ali', 'last_name': 'Grook'}

6. Returning a list

As defined above function can return list as well  as return value. See below example.

Program

def name(first, last, middle=''):
  full_name = [first, middle, last]
  return full_name

data = name('Adam', 'Grook')
data1 = name('Saik', 'Grook', 'Ali')
print(data, "\n", data1)

Output

['Adam', '', 'Grook']
['Saik', 'Ali', 'Grook']

7. Passing  List as argument

It is useful to pass list as an argument to function sometime. By doing so, function gets the direct access to the content of list. We can pass list of names, shop or even complex objects like list of dictionaries.

Program

def list_of_names(names):
  for name in names:
    message = f"Hello {name}, How are you today?"
    print(message)

list1 = ['Alice', 'Bob', 'Kathy']
list_of_names(list1)

Output

Hello Alice, How are you today?
Hello Bob, How are you today?
Hello Kathy, How are you today?

8. Passing List of dictionaries

Let’s create and pass more complex object i.e list of dictionaries. See below example.

Program

real_list = [
{
  'Alice': 20,
  'Bob': 30,
  'Kathy': 40
},
{
  'Alice': 'Engineer',
  'Bob': 'Doctor',
  'Kathy': 'Helper'
}
]

def list_of_names(names):
  count = 1
  names = names + [{'Alice': 'Nice', 'Bob': 'Great', 'Kathy': 'Super'}]
  for name in names:
     message = f"Element {count} of list:\n{name}"
     print(message)
     count = count+1
  return names

list_of_names(real_list)
print(f"Actual List: {real_list}")

Output

Element 1 of list:
{'Alice': 20, 'Bob': 30, 'Kathy': 40}

Element 2 of list:
{'Alice': 'Engineer', 'Bob': 'Doctor', 'Kathy': 'Helper'}

Element 3 of list:
{'Alice': 'Nice', 'Bob': 'Great', 'Kathy': 'Super'}

Actual List: [{'Alice': 20, 'Bob': 30, 'Kathy': 40}, {'Alice': 'Engineer', 'Bob': 'Doctor', 'Kathy': 'Helper'}]

9. Passing Copy of List as Argument

If we do not want our actual list to get modified by the function, we can pass the copy of list as parameter. This will let the actual list unchanged. Use [:] while passing the list to achieve this functionality.

list_of_names(real_list[:])

10. Passing Arbitrary number of arguments

In some requirement we may not be sure that how many number of arguments should be passed to a function ahead of time. Python lets us use its functionality to pass unknown number of arguments to a function. It basically create an empty tuple when see an argument as unknown number of parameter. It keeps on adding the parameters then based on the values passed to it.

Program

def ingredients(*items):
  message = f"You need {items} to prepare your food"
  print(message)

ingredients('Water', 'Sugar', 'Lemon')
ingredients('Fish')

Output

You need ('Water', 'Sugar', 'Lemon') to prepare your food
You need ('Fish',) to prepare your food

11. Arbitrary Keyword arguments

In some cases we want to pass arbitrary number of arguments but not sure about the type of data we want to pass. Use a function that accepts as many key-value pair as the calling function provides. We can achieve same by using ** as arbitrary argument.

Program

def employee(name, id, **employee_info):
  employee_info['name'] = name
  employee_info['id'] = id
  return employee_info

profile = employee('Adam', '1652', Role='DevOps Lead', CTC='Confidential')
print(f"User Profile: {profile}")

Output

User Profile: {'Role': 'DevOps Lead', 'CTC': 'Confidential', 'name': 'Adam', 'id': '1652'}

Leave a Comment