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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Alvif Sandana Mahardika
Alvif Sandana Mahardika

Written by Alvif Sandana Mahardika

Write code with love. Code Your Life :)

No responses yet

Write a response