Python — Function

Alvif Sandana Mahardika
2 min readApr 1, 2021

Previous post:

Overview

Every programming language has its own way to declare a function. Before we go, what is the function? The function is a block of code that only runs when it is called. Functions can be named according to their purpose. We can pass any data to be processed into function, known as parameters.

Declare a New Function

The function defined by using def keywords, followed by the function’s name, parenthesis, and colon. To call a function, use function’s name followed by parenthesis 😉

declare function (line 2) and call function (line 6)

Arguments

We can pass data into function as arguments. Arguments are specified after function’s name, inside the parenthesis. We can add argument as many as we need by separating them with a comma.

Arguments are often named args in Python Documentation.

For example:

call the function with arguments

Arbitrary Arguments, *args and **kwargs

Add * before the parameter name if you don’t know how many arguments will be passed into the function. In this way, the function will receive a tuple of arguments and can access the item from its index.

We use double asterisk** before the parameter name when we want the function to receive a dictionary of arguments and can access the item from its key.

For example:

*args and *kwargs usages

In Python Documentation, kwargs is short of keyword arguments.

Default Parameter Value

Python accepts default parameter value for the function. You can assign parameters with specific values. When you call the function without parameters, it uses the default value.

default parameter value usage

Return Value

Let the function return value with return keyword. 😁

pass Statement

If you have any reason to make a function that does nothing 😅, use pass keyword to avoid the error.

--

--