Passing parameters to python function

Python Functions

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

Example

Calling a Function

To call a function, use the function name followed by parenthesis:

Example

def my_function():
print(«Hello from a function»)

my_function()

Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:

Example

def my_function(fname):
print(fname + » Refsnes»)

my_function(«Emil»)
my_function(«Tobias»)
my_function(«Linus»)

Arguments are often shortened to args in Python documentations.

Parameters or Arguments?

The terms parameter and argument can be used for the same thing: information that are passed into a function.

From a function’s perspective:

A parameter is the variable listed inside the parentheses in the function definition.

An argument is the value that is sent to the function when it is called.

Number of Arguments

By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.

Example

This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):
print(fname + » » + lname)

Example

This function expects 2 arguments, but gets only 1:

def my_function(fname, lname):
print(fname + » » + lname)

Arbitrary Arguments, *args

If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.

This way the function will receive a tuple of arguments, and can access the items accordingly:

Example

If the number of arguments is unknown, add a * before the parameter name:

def my_function(*kids):
print(«The youngest child is » + kids[2])

Читайте также:  Типы данных java final

my_function(«Emil», «Tobias», «Linus»)

Arbitrary Arguments are often shortened to *args in Python documentations.

Keyword Arguments

You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Example

def my_function(child3, child2, child1):
print(«The youngest child is » + child3)

my_function(child1 = «Emil», child2 = «Tobias», child3 = «Linus»)

The phrase Keyword Arguments are often shortened to kwargs in Python documentations.

Arbitrary Keyword Arguments, **kwargs

If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition.

This way the function will receive a dictionary of arguments, and can access the items accordingly:

Example

If the number of keyword arguments is unknown, add a double ** before the parameter name:

def my_function(**kid):
print(«His last name is » + kid[«lname»])

my_function(fname = «Tobias», lname = «Refsnes»)

Arbitrary Kword Arguments are often shortened to **kwargs in Python documentations.

Default Parameter Value

The following example shows how to use a default parameter value.

If we call the function without argument, it uses the default value:

Example

def my_function(country = «Norway»):
print(«I am from » + country)

Passing a List as an Argument

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the function:

Example

def my_function(food):
for x in food:
print(x)

fruits = [«apple», «banana», «cherry»]

Return Values

To let a function return a value, use the return statement:

Example

The pass Statement

function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error.

Example

Recursion

Python also accepts function recursion, which means a defined function can call itself.

Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.

The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.

In this example, tri_recursion() is a function that we have defined to call itself («recurse»). We use the k variable as the data, which decrements ( -1 ) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).

To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and modifying it.

Читайте также:  Остановить работу функции python

Example

def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k — 1)
print(result)
else:
result = 0
return result

print(«\n\nRecursion Example Results»)
tri_recursion(6)

Источник

9 Effective Ways to Pass Parameters to Python Functions

9 Effective Ways to Pass Parameters to Python Functions 1

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.

def vehicle(name, model): print(f"I Own ") print(f"'s Model is ") vehicle('Swift', 'VXI')
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.

def vehicle(model, name): print(f"I Own ") print(f"'s Model is ") vehicle(name='Swift', model='VXI')
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.

def vehicle(model, name='car'): print(f"I Own a ") print(f"'s Model is \n") vehicle(model='VXI') #uses default name value vehicle(name='Swift', model='eco')
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.

def name(first, last, middle=''): full_name = f"  " return full_name data = name('Adam', 'Grook') data1 = name('Saik', 'Ali', 'Grook') print(data,"\n",data1)
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.

def name(first, last, middle=''): full_name = return full_name data = name('Adam', 'Grook') data1 = name('Saik', 'Grook', 'Ali') print(data,"\n",data1)

6. Returning a list

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

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)
['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.

def list_of_names(names): for name in names: message = f"Hello , How are you today?" print(message) list1 = ['Alice', 'Bob', 'Kathy'] list_of_names(list1)
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.

real_list = [ < 'Alice': 20, 'Bob': 30, 'Kathy': 40 >, < 'Alice': 'Engineer', 'Bob': 'Doctor', 'Kathy': 'Helper' >] def list_of_names(names): count = 1 names = names + [] for name in names: message = f"Element of list:\n" print(message) count = count+1 return names list_of_names(real_list) print(f"Actual List: ")
Element 1 of list: Element 2 of list: Element 3 of list: Actual List: [, ]

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.

Читайте также:  301 редирект убрать index php

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.

def ingredients(*items): message = f"You need to prepare your food" print(message) ingredients('Water', 'Sugar', 'Lemon') ingredients('Fish')
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.

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: ")

Источник

Оцените статью