
A function is a reusable piece of code that is usually written to perform a specific task. Functions in Python can be used to organize and avoid repeating code. In this post, you'll get acquainted with Python functions and learn its tricks.
It doesn't matter whether you are new to the Python programming language or have been working with this sweet language for a long time. Surely you have used functions. Perhaps the most used function in Python itself is the print()
function.
With the help of this function, statements related to printing a Python text string are called and printed in the output. Suppose you want to write all the statements related to printing every time you print the text!
In this case, two major problems arise for us:
- We'll have long and busy codes.
- If there is a need to change a part of the code (in this example in the text printing process), we have to change all the parts where we wrote this piece of code.
With the help of functions, we can easily write a piece of code organized with a specific purpose and give it a name. After that, by calling the function name, our piece of code will be executed and there will be no need to write the code again.
Function definition in Python
Python Functions have a specific structure. In order to identify each piece of code, we need to consider a name for them. So all functions have a unique name.
To define a function in Python, the def
keyword is used before its name.
Suppose we want to write a function named myprint()
. This function prints a text string to the Python output. We use print()
to print.
We put a colon (:
) in front of the function name and write the body of the function with an indentation:
def myprint():
print("Hello Hive Blockchain! I'm first albro function!")
congratulations! You have written your first function in Python! Now let's create a professional function…
To call the function (or execute the function), it is enough to call the function name anywhere in the program and define its inputs if necessary.
In the second line and exactly after the function definition, by placing a text string commented with '''
, we can write a description about the function. These descriptions are arbitrary and will be used for future development or when working with programming IDEs.
In the code below, I've written a simple description of my function.
def myprint():
''' This Simple Function Will Print a Static Text '''
print("Hello Hive Blockchain! I'm first albro function!")
function input
The myprint()
function we defined here always prints a fixed text. If we want to give the desired string to the function when it is called, we must define an input for the function itself.
Defining the input for a Python function is very simple. In parentheses in front of the function name, we specify the input name.
If you wanted to define multiple inputs for the function, you can separate them with ,
; Similar to the following function:
def myFunction( arg1, arg2, arg3 ):
# Some Codes Here
When a function is called with its inputs, the input values are placed into these variables. As a result, we take help from these variables (here arg1
, arg2
and arg3
) to read those values in the main body of the function. (Learn more: variable types in Python)
function output
Some functions should give us an output. For example, suppose we define the add()
function to add two numbers. This function must have two inputs and one output.
The inputs are the desired numbers for the addition operation and the output will be the result of our addition.
The keyword return
is used to define the output of the function in Python. return
returns whatever value is in front of it as the output of the function.
def add( a, b ):
return a + b
To understand the exact meaning of the output of the function, consider the following example.
def add( a, b ):
return a + b
a = 10
b = 20
result = add(a,b)
print(result)

In the code above, we send two integers to the function and store the result in the result
variable. Finally, we print the value.
As you can see, if return
was not used in the definition of the add()
function, by executing the third line of the above code, the sum would not be placed in the result
variable.
Tricks of working with Python functions
Defining and using functions in Python is so simple! In the following, I will share with you 2 tricks and 2 tips to become more professional when working with functions.
Pass parameter by reference
All parameters that are in the form of objects are called by reference in Python language. To better understand the topic, let's continue with an example.
Suppose you have a function that takes a list as input. Then it sorts it and prints it in the program environment.
def list_sort( lst ):
lst.sort()
print( "Sorted List is: ", lst )
Now we create a list with jumbled values and pass it to the function to display the result to us.
mylist = [21, 15, 36, 18, 27]
list_sort( mylist )
The output of the code above will give us something like the following:

Now if we print the value of mylist
; To our surprise, we see that our list, which was outside the function, is also sorted in ascending order!
def list_sort( lst ):
lst.sort()
print( "Sorted List is: ", lst )
mylist = [21, 15, 36, 18, 27]
list_sort( mylist )
print( mylist )

but why ?
The reason for this happens is that the parameter is sent by reference. When we call the function along with the list, the list is sent as an object and as Reference to the body of the function. So any changes we make in it will be applied to the main list.
Lambda function or anonymous function in Python
Anonymous functions are not normally defined with the def
keyword. The lambda
keyword is used to define them; For this reason, they are sometimes called Lambda functions.
These functions can take an unlimited number of inputs but have only one output. In fact, they are a kind of linear function.
The definition of Python's anonymous functions is as follows:
lambda arg1, arg2: arg1 + arg2
In the body of this function (the part after :
), only the variables taken as input can be identified.
In the first line of the code below, we have defined a function called pw
to raise two numbers to the power. Then in the second line, we call the function and execute it.
pw = lambda a, b: a**b
print( pw(2,3) )

In general, anonymous functions in Python are used for simple, one-line functions. If your function is more than one line or you are going to do a lot of calculations, using the main function will be the best choice.

Types of function input arguments in Python
In general, four types of input arguments can be defined in Python functions.
- Required arguments
- Keyword arguments
- Argument with default value
- Variable-Length Arguments
Defining the required argument for a Python function
In the examples so far, all required arguments have been used. A required argument is an argument that must be set when the function is called.
Remember the example of the add()
function to add two numbers.
def add( a, b ):
return a + b
If we call the function with no arguments, with one argument, or with more than two arguments, we will encounter a TypeError
error.
add( 5 )
# Traceback (most recent call last):
# File "run.py", line 7, in
# add( 5 )
# TypeError: add() missing 1 required positional argument: 'b'
So by defining such arguments, the end user who is using the function will have to send all the inputs we need to the function; Otherwise, an error message will be displayed.
Define the keyword argument
This type of argument definition is no different from the normal definition. The difference between keyword arguments is on how to call them.
Suppose we have the pw()
function below to exponentiate a number.
def pw( base, power ):
print( base**power )
To call the function, we can act as follows.
pw( 2, 3 )
# 8
The other mode (calling with the help of the keyword) of the same function is as follows.
pw( base=2, power=3 )
# 8
pw( power=3, base=2 )
# 8

As you can see in this example, the order of the inputs does not matter in this type of call. Each entry will be recognized and valued according to its name.
Defining an argument with a default value in Python
We may want to define a function in Python where all or some of its input arguments are optional. In this way, if that argument is not initialized during the call, consider a default value for it.
In the last example, we want to change the function so that if the power input is not defined, its value will be 1. For this, we act as follows.
def pw( base, power=1 ):
print( base**power )
simply! We have assumed a default value for the argument by placing an equal sign (=
) and defining the desired value.
With the help of this method, an arbitrary argument is practically defined for the Python function.
Variable-Length Arguments for the function
In few functions, the number of inputs is not known in advance, or more precisely, we want the number of arguments to be variable. To define the number of variable arguments for the Python function, the Variable-Length Arguments method is used.
We want to write a function to calculate the average of numbers. We have two methods to get input:
The first method is to use a list to get the numbers and the second method is to use a variable length argument.
To define an argument with variable length, it is enough to put an asterisk (*
) before the name of the input variable. With this, all the entries after that variable will be placed in that variable as a Python tuple and will be available to us in the body of the function.
We write the average()
function using Python for
loop to calculate the average of an unknown number of numbers as follows.
def average( *vals ):
total = 0
for val in vals:
total += val
return total/len(vals)
Now this function can be called with as many input arguments as we want!
average(5)
# 5.0
average(1, 2, 3, 4, 5)
# 3.0
average(1, 3, 5, 7, 9, 11, 13, 15)
# 8.0
Summary: Functions and tricks in Python
In this post, we learned how to define a function in Python. Functions are defined with the def
keyword and have a name. You can also define different arguments for it as input.
Functions in Python consist of three main parts:
- The name and definition section of entries
- Main body part
- The final part
In the final part of the function, with the help of return
, we can return the final calculated values as the output of the function.