Python Functions – Engage into the Functions of Python Programming

Python is object-oriented but also supports functional programming. In this tutorial, you will learn about Python functions and will learn to create them and call them. Also, you will get to understand the parameters of functions in Python, the return statement, anonymous functions in Python, and lastly, you will see what is recursion in Python.

What are Functions?

A function is a block of code that has a name and you can call it. Instead of writing something 100 times, you can create a function and then call it 100 times. You can call it anywhere and anytime in your program. This adds reusability and modularity to your code. Functions can take arguments and return values.

Types of Python Functions

Functions can be of two types – built-in or user-defined. Python has many useful built-in functions like print() and type() but in this article, we will focus on user-defined functions.

Creating Functions in Python

To define a function, we follow this syntax:

Syntax:

def func(parameters):
  code
  return

To define a function, you use the def keyword. You give the function a name and it can take some parameters if you want. Then you specify a block of code that will execute when you call the function. There are no curly braces in Python and so you need to indent this code block otherwise it won’t work. You can make the function return a value.

Let’s take an example for you.

Code:

def add(a,b):
  print("I will add two numbers")
  return a+b

This function prints “I will two numbers” and returns the sum of two numbers.

Code:

>>> add(2,4)

Output:

I will add two numbers
6

Calling Functions in Python

Calling functions is simple. Take two functions:

Code:

def sayhi():
  print('Hi')

Code:

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

This is how you will call them:

Code:

>>> sayhi()

Output:

Hi

Code:

>>> add(2,4)

Output:

6

Python Function Parameterspython function parameters

Functions can take values and operate on them. In the above example, the add() function takes parameters a and b.

Python has 3 types of parameters or arguments other than positional/required arguments – default, keyword, arbitrary.

1. Default Arguments

You can specify a default value for arguments. If the user calls the function, they can skip providing a value for that argument. The default value is used.

Code:

def add(a, b=4):
  return a+b

Now you can call it with one or two values.

Code:

>>> add(2,4)

Output:

6

Code:

>>> add(2)

Output:

6

Here b is 4 by default so it returns 2+4, which is 6. Functions can have any number of default arguments.

2. Keyword Arguments

If you pass keyword arguments to a function, you don’t need to remember the order of the parameters.

Code:

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

Code:

>>> add(b=4,a=2)

Output:

6

3. Arbitrary Arguments

If you don’t know how many arguments your function will get at runtime, you can use the arbitrary arguments *args and **kwargs.

*args is a variable number of arguments and **kwargs is a variable number of keyword arguments. You can call them anything.

Code:

def add(*args,**kwargs):
  result=0
  for arg in args:
    result+=arg
  print(result)
  for key,value in kwargs.items():
    print(key,value)

Code:

>>> add(2,4,6,a=8,b=10)

Output:

12
a 8
b 10

2, 4, 6, are in *args and a=8 and b=10 are in **kwargs. result is 12.

You cannot pass positional arguments after keyword arguments.

Code:

>>> add(2,4,6,a=8,7,b=10)

Output:

SyntaxError: positional argument follows keyword argument

The Return Statement in Python

It is not mandatory for a function to return a value but it can. For this, you use the return keyword.

Code:

def show_names(names):
  return names

Code:

>>> show_names(['Jack', 'Paris', 'Nicole'])

Output:

[‘Jack’, ‘Paris’, ‘Nicole’]

This function returns a list.

Anonymous Functions in Python

If you want a function only once or it has only one line of code, you can avoid giving it a name. They are called lambda expressions.

Code:

>>> lambda a=2,b=4:a+b
<function <lambda> at 0x00000198A3692168>

Now to call this:

Code:

>>> (lambda a=2,b=4:a+b)()

Output:

6

Let’s try more possibilities.

Code:

>>> (lambda a,b:a+b)(2,4)

Output:

6

Code:

>>> add=lambda a,b:a+b
>>> add(2,4)

Output:

6

Code:

>>> (lambda :print('Hi'))()

Output:

Hi

Recursion in Python

When a function calls itself, it is recursion. In other words, when a function body has calls to the function itself, it is recursion. For recursion, you should specify a base condition otherwise the function can execute infinitely. Let’s take the example of calculating factorials.

Code:

def factorial(num):
  if num==1: return 1
  return num*factorial(num-1)

Code:

>>> factorial(4)

Output:

24

factorial(4) returns 4*factorial(3). factorial(3) returns 3*factorial(2). factorial(2) returns 2*factorial(1). factorial(1) returns 1. So we have 4*3*2*1. This is equal to 24. So it returns the value 24.

Summary

We will explain these topics in detail in other tutorials. This was a brief introduction of TechVidvan’s Python functions article. We learned about functions, creating them, calling them, parameters, the return statement, lambda expressions, and recursion.

If you liked TechVidvan’s Python functions article, do recommend us on Facebook.

Happy Learning!!

3 Responses

  1. Himanshu goyal says:

    I am a beginner.which tutorial to take first.i don’t see any order.
    Articles are very good.

    • TechVidvan Team says:

      Hi Himanshu,

      You can refer to the sidebar. The Python tutorials are arranged in a sequential manner designed from beginner to advanced level.

  2. sajadin s says:

    your articel is very good
    thank you

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.