Python Function Tutorial – Type of Functions in Python(With Example)

1. Python Function – Objective

In our tutorial, we discussed dictionaries in pythonNow, we forward to deeper parts of the language, let’s read about Python Function. Moreover, we will study the different types of functions in Python: Python built-in functions, Python recursion function, Python lambda function, and Python user-defined functions with their syntax and examples.

So, let’s start the Python Function Tutorial.

Python Function Tutorial - Type of Functions in Python(With Example)

Python Function Tutorial – Type of Functions in Python(With Example)

Learn: Range Function in Python – Range() in Python

2. An Introduction to Function in Python

Python function in any programming language is a sequence of statements in a certain order, given a name. When called, those statements are executed. So we don’t have to write the code again and again for each [type of] data that we want to apply it to. This is called code re-usability.

3. User-Defined Functions in Python

For simplicity purposes, we will divide this lesson into two parts. First, we will talk about user-defined functions in Python. Python lets us group a sequence of statements into a single entity, called a function. A Python function may or may not have a name. We’ll look at functions without a name later in this tutorial.

a. Advantages of User-defined Functions in Python

  1. This Python Function help divide a program into modules. This makes the code easier to manage, debug, and scale.
  2. It implements code reuse. Every time you need to execute a sequence of statements, all you need to do is to call the function.
  3. This Python Function allow us to change functionality easily, and different programmers can work on different functions.

b. Defining a Function in Python

To define your own Python function, you use the ‘def’ keyword before its name. And its name is to be followed by parentheses, before a colon(:).

>>> def hello():
          print("Hello")

The contents inside the body of the function must be equally indented.

As we had discussed in our article on Python syntax, you may use a docstring right under the first line of a function declaration. This is a documentation string, and it explains what the function does.

>>> def hello():
             """
             This Python function simply prints hello to the screen
             """
             print("Hello")

You can access this docstring using the __doc__ attribute of the function.

>>> def func1():
           """
           This is the docstring
           """
           print("Hello")
>>> func1.__doc__
'\n\tThis is the docstring\n\t'

However, if you apply the attribute to a function without a docstring, this happens.

>>> sum.__doc__
>>> type(sum.__doc__)
<class 'NoneType'>
>>> bool(sum.__doc__)

False

If you don’t yet know what to put in the function, then you should put the pass statement in its body. If you leave its body empty, you get an error “Expected an indented block”.

>>> def hello1():
       pass
>>> hello1()

You can even reassign a function by defining it again.

Learn Methods in Python – Classes, Objects and Functions in Python

c. Rules for naming python function (identifier)

We follow the same rules when naming a function as we do when naming a variable.

  1. It can begin with either of the following: A-Z, a-z, and underscore(_).
  2. The rest of it can contain either of the following: A-Z, a-z, digits(0-9), and underscore(_).
  3. A reserved keyword may not be chosen as an identifier.

It is good practice to name a Python function according to what it does.

Learn Python Dictionaries with Methods, Functions and Dictionary Operations

d. Python Function Parameters

Sometimes, you may want a function to operate on some variables, and produce a result. Such a function may take any number of parameters. Let’s take a function to add two numbers.

>>> def sum(a,b):
            print(f"{a}+{b}={a+b}")
>>> sum(2,3)

2+3=5

Here, the function sum() takes two parameters- a and b. When we call the function, we pass numbers 2 and 3. These are the arguments that fit a and b respectively. We will describe calling a function in point f. A function in Python may contain any number of parameters, or none.

In the next example, we try adding an int and a float.

>>> def sum2(a,b):
         print(f"{a}+{b}={a+b}")
>>> sum2(3.0,2)

3.0+2=5.0

However, you can’t add incompatible types.

>>> sum2('Hello',2)

Traceback (most recent call last):

File “<pyshell#39>”, line 1, in <module>

sum2(‘Hello’,2)

File “<pyshell#38>”, line 2, in sum2

print(f”{a}+{b}={a+b}”)

TypeError: must be str, not int

Learn Python Strings with String Functions and String Operations

e. Python return statement

A Python function may optionally return a value. This value can be a result that it produced on its execution. Or it can be something you specify- an expression or a value.

>>> def func1(a):
         if a%2==0:
               return 0
          else:
                return 1
>>> func1(7)

1

As soon as a return statement is reached in a function, the function stops executing. Then, the next statement after the function call is executed. Let’s try returning an expression.

>>> def sum(a,b):
         return a+b
>>> sum(2,3)

5

>>> c=sum(2,3)

This was the Python Return Function

f. Calling a Python function

To call a Python function at a place in your code, you simply need to name it, and pass arguments, if any. Let’s call the function hello() that we defined in section b.

>>> hello()

Hello

We already saw how to call python function with arguments in section e.

Learn: Python Operators with Syntax and Examples

g. Scope and Lifetime of Variables in Python

A variable isn’t visible everywhere and alive every time. We study this in functions because the scope and lifetime for a variable depend on whether it is inside a function.

1. Scope

A variable’s scope tells us where in the program it is visible. A variable may have local or global scope.

  • Local Scope- A variable that’s declared inside a function has a local scope. In other words, it is local to that function.
>>> def func3():
        x=7
        print(x)
>>> func3()

7

If you then try to access the variable x outside the function, you cannot.

>>> x

Traceback (most recent call last):

File “<pyshell#96>”, line 1, in <module>

x

NameError: name ‘x’ is not defined

  • Global Scope- When you declare a variable outside python function, or anything else, it has global scope. It means that it is visible everywhere within the program.
>>> y=7
>>> def func4():
          print(y)
>>> func4()

7

However, you can’t change its value from inside a local scope(here, inside a function). To do so, you must declare it global inside the function, using the ‘global’ keyword.

>>> def func4():
      global y
      y+=1
      print(y)
>>> func4()

8

>>> y

8

As you can see, y has been changed to 8.

Learn: Python Variables and Data Types with Syntax and Examples

2. Lifetime

A variable’s lifetime is the period of time for which it resides in the memory.

A variable that’s declared inside python function is destroyed after the function stops executing. So the next time the function is called, it does not remember the previous value of that variable.

>>> def func1():
         counter=0
         counter+=1
         print(counter)
>>> func1()

1

>>> func1()

1

As you can see here, the function func1() doesn’t print 2 the second time.

h. Deleting Python function

Till now, we have seen how to delete a variable. Similarly, you can delete a function with the ‘del’ keyword.

>>> def func7():
        print("7")
>>> func7()

7

>>> del func7
>>> func7()

Traceback (most recent call last):

File “<pyshell#137>”, line 1, in <module>

func7()

NameError: name ‘func7’ is not defined

When deleting a function, you don’t need to put parentheses after its name.

Different Python Function Explained Below.

Learn: Python Installation Tutorial – Steps to Install Python on Windows

4. Python Built-in Functions

In various previous lessons, we have seen a range of built-in functions by Python. This Python function apply on constructs like int, float, bin, hex, string, list, tuple, set, dictionary, and so. Refer to those lessons to revise them all.

5. Python Lambda Expressions

As we said earlier, a function doesn’t need to have a name. A lambda expression in Python allows us to create anonymous python function, and we use the ‘lambda’ keyword for it. The following is the syntax for a lambda expression.

lambda arguments:expression

It’s worth noting that it can have any number of arguments, but only one expression. It evaluates the value of that expression, and returns the result. Let’s take an example.

>>> myvar=lambda a,b:(a*b)+2
>>> myvar(3,5)

17

This code takes the numbers 3 and 5 as arguments a and b respectively, and puts them in the expression (a*b)+2. This makes it (3*5)+2, which is 17. Finally, it returns 17.

Actually, the function object is assigned to the identifier myvar.

Learn: Python Arguments with Types, Syntax and Examples

Any Doubt yet in Python Function? Please Comment.

Python Interview Questions

6. Python Recursion Function

A very interesting concept in any field, recursion is using something to define itself. In other words, it is something calling itself. In Python function, recursion is when a function calls itself. To see how this could be useful, let’s try calculating the factorial of a number. Mathematically, a number’s factorial is:

n!=n*n-1*n-2*…*2*1

To code this, we type the following.

>>> def facto(n):
        if n==1:
                return 1
            return n*facto(n-1)
>>> facto(5)

120

>>> facto(1)

1

>>> facto(2)

2

>>> facto(3)

6

This was all about recursion function in Python

Isn’t this handy? Tell us where else would you use recursion. However, remember that if you don’t mention the base case (the case which converges the condition), it can result in an infinite execution.

Learn: Learn Python Closure – Nested Functions and Nonlocal Variables

This was all about the Python Function

7. Conclusion: Python Function

It is important to revise in order to retain information. In this lesson, we learned about the Python function. First, we saw the advantages of a user-defined function in Python. Now we can create, update, and delete a function. And we know that a function may take arguments and may return a value. We also looked at the scope and lifetime of a variable. Hope you like the Python Function Tutorial.

Don’t forget to revise the various built-in functions supported by Python. Refer to our tutorials for the same.

Reference

1 Response

  1. Venkatesh says:

    hi can i get full pdf of your python notes.

Leave a Reply

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