10+ simple examples to learn Python functions in detail


Written by - Deepak Prasad

In this tutorial we will learn about python functions and it's usage covering different scenarios and types.

1. Why use Python functions?

  • Functions provide a way to compartmentalize your code into small tasks that can be called from multiple places within a program
  • This is especially useful if the code in question will be used several times in different parts of your program.
  • You may want to use functions to abstract away some complex code that you need in your programs.
  • You can think of functions as mini-programs within your bigger program that implement specific tasks.
  • The general rule of thumb is that if you have a block of code that gets called more than once, put it in a function.
  • Functions may take optional inputs to work with and may optionally return a value or values.

2. Different types of functions in Python

The three main types of functions in Python are as follows:

3. Built-in function

The Python interpreter has a number of built-in functions and types that are always available. These are called built-in functions, and they can be used anywhere in your code, without the need of any importation.

We have already used multiple in-built functions throughout out Python tutorial such as print(), sorted(), type() etc. To get the complete list of python built-in functions you can check the official python page .

4. User-defined function

As the name suggests, these are functions that are written by the user, to aid them in achieving a specific goal. The main use of functions is to help us organize our programs into logical fragments that work together to solve a specific part of our problem.

4.1 General structure of Python function (Syntax)

The structure of a function is very simple but very important.

def {FunctionName}[(parameters)]: # Function Header
  Indented code..... # Code begins here
  return
  • Use the def keyword, followed by the function name.
  • The function name must follow the same naming rules for variables (Single word, No spaces, must start with either a letter or an underscore, etc).
  • Add parameters (if any) to the function within the parentheses. End the function definition with a full colon.
  • Write the logic of the function. All code for the function must be indented.
  • Finally, use the return keyword to return the output of the function. This is optional, and if it is not included, the function automatically returns None.

4.2 Create function in Python

To create a function, start a new line with def (short for definition) followed by a space, and then a name of your own choosing followed by a pair of parentheses with no spaces before or inside. Then put a colon at the end of that line.

Here I have created a simple function to add two integers:

10+ simple examples to learn Python functions in detail

Output from this script:

~]# python3 create-function.py
30

This is a very simple function where we have defined global variables num1 and num2 which are used within the function to add both the numbers and store the value in total. Next we print the value of total variable. Lastly we call the function by using the function name calculate()

NOTE:
Indentations count big time in Python. There is no command that marks the end of a function. All indented lines below the def line are part of that function. The first un-indented line (indented as far out as the def line) is outside the function.

4.3 Returning values in function

There will be times that your function needs to return one or more values. We use the return keyword to do this. Without a return statement, every function will return None.

In this example script I am passing two values to the function (don't worry we will cover this part in detail later in this tutorial) and later we will just return those values. When we call the function, we assign two variables (a and b) to hold the two returned values.

10+ simple examples to learn Python functions in detail

Output from this script:

 ~]# python3 return-values.py
Returned from function: 5,10

4.4 Passing arguments or parameters to function

Parameters are the information that need to be passed to the function for it to do its work. Although parameters are also commonly referred to as arguments, arguments are thought of more as the actual values or references assigned to the parameter variables when a function is called at runtime.

Python supports several types of arguments; namely:

  • Required arguments
  • Keyword arguments
  • Default arguments
  • A variable number of arguments

4.5 Required arguments

Required arguments are the types of arguments that have to be present when calling a function. These types of arguments also need to be in the correct order for the function to work as expected.

10+ simple examples to learn Python functions in detail

Output from this script:

 ~]# python3 mandatory-args.py
Output of our function is:  5.0

Now here I have provided the input arguments in the order which it was expected where the first value is then dividend while second number is the divisor.

But what if we switch the position of both arguments?

10+ simple examples to learn Python functions in detail

The output also changes accordingly:

~]# python3 mandatory-args.py
Output of our function is:  0.2

So it is important that we pass the arguments to the function in the same order as it will be used within the function.

4.6 Keyword Arguments

Actually if it is necessary that you call all of the parameters in the right order, you can use keyword arguments in your function call. You can use these to identify the arguments by their parameter names.

In this example I have defined the keywords while passing the arguments to the function, so even if I switch the order it wouldn't matter as the values are assigned to the keyword itself.

10+ simple examples to learn Python functions in detail

Output from this script:

~]# python3 keyword-args.py
Output of our function is:  5.0

Keyword arguments are very powerful, and they ensure that no matter which order we pass arguments in, the function will always know which argument goes where.

4.7 Default arguments

Default arguments are those that take a default value if no argument value is passed during the function call. You can assign this default value with the assignment operator = as we have done in this example script. Here we are passing single input argument to our function for first, while for second we have assigned a default value already.

10+ simple examples to learn Python functions in detail

Output from this script:

~]# python3 default-args.py
Output of our function is:  5.0

Note that even if the argument named second has a default value, you can still pass a value to it, and this passed value will override the default value. This means that the function will promptly ignore the default value and use whatever value you passed to it.

In this example I have used keyword argument to assign second=5 while I already have assigned a default value second=2. In such case, the argument which is passed to the function i.e. second=5 will take precedence.

10+ simple examples to learn Python functions in detail

Output from this script:

~]# python3 default-args.py
Output of our function is:  2.0

4.8 Variable number of arguments

You can also design the function so that it accepts any number of arguments. It's not particularly faster or better, so there’s no “right time” or “wrong time” to use this method. Just use whichever seems easiest to you, or whichever seems to make the most sense at the moment. To pass in any number of arguments, use *args as the parameter name, like this:

def testFunc(*args)

Whatever you pass in becomes a tuple named args inside the function.

10+ simple examples to learn Python functions in detail

Output from this script:

 ~]# python3 variable-args.py
<class 'tuple'>
Output of our function is:  40

As you can see the arguments passed to the function are added as Tuple. Please NOTE that here I have used <strong>*args</strong> but you can use any other name such as <strong>*numbers</strong>

5. Anonymous functions (lambda)

  • Python supports the concept of anonymous functions, also called lambda functions.
  • The anonymous part of the name is based on the fact that the function doesn't need to have a name (but can have one if you want it to).
  • The lambda part is based on the use of the keyword lambda to define them in Python.
  • These functions are usually throwaway, meaning that they are only required where they are defined, and are not to be called in other parts of the codebase.

The syntax of an anonymous function is as follows:

lambda arguments: expression

When using it:

  • Replace arguments with data being passed into the expression.
  • Replace expression with an expression (formula) that defines what you want the lambda to return.

5.1 When should I use lambda function?

Let me start from the basics to help you understand the concept.

Here I have a small script where I wish to sort the strings part of names list. Now strings are sorted alphabetically so I would expect the output sorted in A-Z format:

10+ simple examples to learn Python functions in detail

Output from this script:

 ~]# python3 lambda-function.py
['Avni', 'Ravi', 'amit', 'bhavin']

Here Avni and Ravi are printed in proper order but other strings starting with lower character are placed near the last of the list i.e. amit and bhavin even though alphabetically they should be first in the list

The reason is because the sort is based on ASCII, which is a system in which each character is represented by a number. All the lowercase letters have numbers that are higher than uppercase numbers. So, when sorting, all the words starting with lowercase letters come after the words that start with an uppercase letter.

We can use str.transform() to transform the case and then perform the sorting

10+ simple examples to learn Python functions in detail

The output contains lowercase first now but it is still not properly sorted:

 ~]# python3 lambda-function.py
['Avni', 'Ravi', 'amit', 'bhavin']
sort with swapcase ['amit', 'bhavin', 'Avni', 'Ravi']

Now we can't use key=lower in the sort() parentheses because lower() isn't a built-in function so we can create a function which will transform the case of all the elements part of out list and use this function as key to transform the case and then perform the sorting.

10+ simple examples to learn Python functions in detail

Here our function convert_lower will take single input argument and store it in anystring which will be transformed into lowercase. Running this code to display the list of names puts them in the correct order, because it based the sort on strings that are all lowercase. The output is the same as before because only the sorting, which took place behind the scenes, used lowercase letters. The original data is still in its original uppercase and lowercase letters.

~]# python3 lambda-function.py
Default sorting ['Avni', 'Ravi', 'amit', 'bhavin']
sort with convert_lower function ['amit', 'Avni', 'bhavin', 'Ravi']

Now we have solved the problem, we have not yet used lambda function?

There is no lambda function yet. But this is a perfect example of where you could use a lambda function, because the function you’re calling, lowercaseof(), does all of its work with just one line of code: return anystring.lower().

When your function can do its thing with a simple one-line expression like that, you can skip the def and the function name and just use this syntax:

lambda parameters : expression

Replace parameters with one or more parameter names that you make up yourself (the names inside the parentheses after def and the function name in a regular function). Replace expression with what you want the function to return without the word return. So in this example the key, using a lambda expression, would be:

lambda anystring : anystring.lower()

Here is our final script:

#!/usr/bin/env python3

def convert_lower(anystring):
    # converts anystring to lowercase and returns
    return anystring.lower()

# Define a list
names = ['Avni', 'Ravi', 'amit', 'bhavin']

names.sort() ## sort the strings within the list
print('Default sorting', names) ## print sorted output

names.sort(key=lambda anystring: anystring.lower()) ## use lambda function to transform
print('sort with lambda function', names)

You can use any variable instead of anystring in this example. Output from this script:

 ~]# python3 lambda-function.py
Default sorting ['Avni', 'Ravi', 'amit', 'bhavin']
sort with lambda function ['amit', 'Avni', 'bhavin', 'Ravi']

6. Conclusion

In this tutorial you learned all about python functions and how to create your own custom functions in Python. We covered how and where to apply the different types of functions, and how they can be used to help break your programs into smaller sub-programs that achieve a specific purpose. We also saw how the use of functions can help use reuse functionality in our code and avoid repeating the same blocks of code.

In real life, what you want to do is, any time you find that you need access to the same chunk of code — the same bit of login — over and over again in your app, don’t simply copy/paste that chunk of code over and over again. Instead, put all that code in a function that you can call by name.

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can reach out to him on his LinkedIn profile or join on Facebook page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment

X