DEV Community

Cover image for PYTHON FUNCTION
digitalcontentf
digitalcontentf

Posted on

PYTHON FUNCTION

Function is a piece of code written to carry out a specified task. They are set of bundled instructions that you want to use repeatedly or that, because of their complexity, are better self-contained in a sub-program and called when needed To carry out that specific task, the function might or might not need multiple inputs. When the task is carried out, the function can or cannot return one or more values.
There are three types of functions in Python:
(1) Built-in functions, such as help() to ask for help, min() to get the minimum value, print() to print an object to the terminal,… You can find an overview with more of these functions here.
(2) User-Defined Functions (UDFs), which are functions that users create to help them out; And
(3) Anonymous functions, which are also called lambda functions because they are not declared with the standard def keyword.

Define a function plus()

def plus(a,b):
return a + b

Create a Summation class

class Summation(object):
def sum(self, a, b):
self.contents = a + b
return self.contents

Parameters vs Arguments
Enter fullscreen mode Exit fullscreen mode

Parameters are the names used when defining a function or a method, and into which arguments will be mapped. In other words, arguments are the things which are supplied to any function or method call, while the function or method code refers to the arguments by their parameter names.

Consider the following example and look back to the above DataCamp Light chunk: you pass two arguments to the sum() method of the Summation class, even though you previously defined three parameters, namely, self, a and b.

What happened to self?

The first argument of every class method is always a reference to the current instance of the class, which in this case is Summation. By convention, this argument is called self.

This all means that you don’t pass the reference to self in this case because self is the parameter name for an implicitly passed argument that refers to the instance through which a method is being invoked. It gets inserted implicitly into the argument list.

How To Define A Function: User-Defined Functions (UDFs)
The four steps to defining a function in Python are the following:

Use the keyword def to declare the function and follow this up with the function name.
Add parameters to the function: they should be within the parentheses of the function. End your line with a colon.
Add statements that the functions should execute.
End your function with a return statement if the function should output something. Without the return statement, your function will return an object None.

def hello():
print("Hello World")
return

How To Call A Function
In the previous sections, you have seen a lot of examples already of how you can call a function. Calling a function means that you execute the function that you have defined - either directly from the Python prompt or through another function (as you will see in the section “Nested Functions”).

Call your newly defined function hello() by simply executing hello(), just like in the DataCamp Light chunk below:

How To Add Docstrings To A Python Function
Another essential aspect of writing functions in Python: docstrings. Docstrings describe what your function does, such as the computations it performs or its return values. These descriptions serve as documentation for your function so that anyone who reads your function’s docstring understands what your function does, without having to trace through all the code in the function definition.

Function docstrings are placed in the immediate line after the function header and are placed in between triple quotation marks. An appropriate Docstring for your hello() function is ‘Prints “Hello World”’.

def hello():
"""Prints "Hello World".

Returns:
None
"""
print("Hello World")
return

Function Arguments in Python
Earlier, you learned about the difference between parameters and arguments. In short, arguments are the things which are given to any function or method call, while the function or method code refers to the arguments by their parameter names. There are four types of arguments that Python UDFs can take:

(a) Default arguments
(b) Required arguments
(c) Keyword arguments
(d) Variable number of arguments

Anonymous Functions in Python
Anonymous functions are also called lambda functions in Python because instead of declaring them with the standard def keyword, you use the lambda keyword.

double = lambda x: x*2

double(5)

You use anonymous functions when you require a nameless function for a short period of time, and that is created at runtime. Specific contexts in which this would be relevant is when you’re working with filter(), map() and reduce():
The filter() function filters, as the name suggests, the original input list my_list on the basis of a criterion >10. With map(), on the other hand, you apply a function to all items of the list my_list. In this case, you multiply all elements with 2.

Note that the reduce() function is part of the functools library. You use this function cumulatively to the items of the my_list list, from left to right and reduce the sequence to a single value, 55, in this case.

Using main() as a Function
If you have any experience with other programming languages such as Java, you’ll know that the main function is required to execute functions. As you have seen in the examples above, this is not necessarily needed for Python. However, including a main() function in your Python program can be handy to structure your code logically - all of the most important components are contained within this main() function.

You can easily define a main() function and call it just like you have done with all of the other functions above:

Define main() function

def main():
hello()
print("This is a main function")

main()

Top comments (0)