Functions in Python | Types, Example

A function in Python is a named block of organized and connected statements that performs a specific task.

In other words, a function is a block of code that performs a specific and well-defined task. It organizes the code into a logical way to perform a certain task.

Every function is called by a certain name and the block of code inside the function gets executed when we call the function.

If you have a block of code that gets invoked more than once, put it into a function. This is because function allows us to use a block of code repeatedly in different sections of a program.

It makes the program more efficient by minimizing the repetition. It makes the code reusable.

Functions help to break down long and complex programs into smaller and manageable segments and enhance program readability and comprehensibility.

They provide better modularity for our application program and a high degree of code reusability. Sometimes, we call the function with another name called method. But, there is a slight difference between a function and method.

Functions are defined outside the class, whereas methods are defined inside the class.

Why do we need to use functions in Python?

A function is a piece of code in a program that performs a specific task. Following are some key reasons for using functions in Python. They are:

1. Functions help to reduce the duplicate code. They can make a long program into smaller. We can avoid the repetition of frequently required code using functions.

Later, if we need to make a change in the code, we can easily update it in one place. Hence, debugging of code becomes easy.

2. Breaking up of a long and complex program into functions allows us to debug each segment one at a time and then assemble them into a working whole.

3. We can group together all logically related statements in one entity using functions in Python. Function makes the program easy to read, understand, and debug. It improves the clarity of the code.

4. Once we write the code inside the function and test it, we can reuse this code as per the requirement. Reusability is the significant use of functions in Python.

Syntax to define User defined Function in Python

The user creates or defines user-defined functions. The general syntax to declare a user defined function in Python is as follows:

def function_name(parameters): # Function header.
    . . . . . .
    body of the function
    . . . . . .
    return [expression or values]

In the above syntax, the first line of function definition is header, and the rest is the body of function. The function definition begins with def keyword followed by the function name, parentheses (()), and then colon (:). The parameter list placed within parentheses is optional.

Let’s define a simple function that prints the message “Hello Python”.

# Function definition.
def msg():
    """This statement prints a message."""
    print('Hello Python')

Components of Python Functions

A block of statements that defines a function in Python consists of the following parts:Python functions definition

1. Keyword def:

Function definition starts with the keyword ‘def’ that defines the function. It tells the beginning of the function header.

2. Function name:

The function_name represents the name of a function. Every function must be a unique user-defined name or an identifier and given to it in the function header statement.

It is an excellent practice to name your function according to the work it performs. In the above example, the function name is msg, and add.

3. Parameters:

The formal parameters (arguments) placed inside the parentheses are optional. A parameter is a piece of data or information that we use inside the function to perform a specific task.

Generally, parameters are a list of local variables that will be assigned with values when the function gets called. They are used to passing values to functions.

They can be zero, or more parameters, separated by commas inside the parentheses. In the above example, there are two parameters in the function definition.

4. Colon (:):

A colon indicates the end of function headers.

5. Docstring:

A docstring is a documentation string that is an optional component. We commonly use it to describe what the function does. We write it on the line next to the function header.

A docstring must enclose in triple quotes and can write up to in several lines. We can access it with: function_name.__doc__.

6. Statement(s):

The body of function consists of one or more valid statements. Each statement must be intended with the same indentation to form a block.

In general, 4 spaces of indentation are standard from the header line in Python. When the function gets called, the statements inside the function’s body execute.

Once the function is invoked, the formal parameters inside the parentheses become arguments.

7. Return statement:

A return statement ends the function call and returns a value from a function back to the calling code. It is optional. If we do not define return statement inside the function’s body, the function returns the object ‘None’.

We will learn about the return statement in the further tutorial in more detail.

Rules for defining User defined Function in Python

There are the following important rules for defining the user-defined functions in Python that should you keep in your mind. They are as:

1. Functions must begin either with a letter or an underscore.

2. They should be lowercase.

3. They can comprise numbers but shouldn’t begin with one.

4. Functions can be of any length.

5. The name of function should not be a keyword in Python.

6. We can use an underscore to separate more than one word. For example, function_name(), person_name(), etc. It improves the readability and maintains conventions.

7. There should not be any space between the two words.

Types of Functions in Python

There are two types of functions available in Python programming language. They are:

  • Built-in functions
  • User-defined functions

Let’s discuss each one in detail with the help of example.

Built-in Functions in Python

Built-in functions in Python are predefined functions by the Python system. They allow us to perform a variety of tasks, such as printing messages, converting one type of data to another, etc.

The predefined functions are always available to use. We do not need to import required module for them. Python comes with a variety of built-in functions. Some of the commonly used built-in functions are as:

1. abs(value): This function returns the absolute value of a given numeric value. Let’s take an example of it.

# This statement return the absolute value of a number.
num = abs(-5.45)
print(num) # Output: 5.45

2. bin(n): This function returns a binary representation of a integer number. For example:

# This statement return the binary representation of a number.
num = bin(24)
print(num) # Output: 0b11000

3. float(n): It returns a floating-point number of a given number. For example:

# Converting an integer number 5 into a floating-point number.
num = float(5)
print(num) # Output: 5.0

4. int(n): It returns an integer number of a specified number. For example:

# Converting a floating-point number 5.5 into an integer number.
num = int(5.5)
print(num) # Output: 5

5. sqrt(x): This function returns the square root of a given number. For example:

# Finding the square root of a number 36.
import math
sq_num = math.sqrt(36)
print('Square of number 36 = ',sq_num)
      Square of number 36 =  6.0

6. pow(x, y): This function returns the value of x raised to the power y. For example:

# Finding the value of 4 to the power of 2.
import math
pw_num = math.pow(4,2)

7. factorial(x): This function finds the factorial of a specified number. For example:

# Finding the factorial of number 5.
import math
fact_num = math.factorial(5)
print('Factorial of number 5 = ',fact_num)
      Factorial of number 5 =  120

8. len(iterable): This function returns the number of elements or items of the specified iterable object. For example:

# Returns the number of elements in the list.
city_list = ['Dhanbad', 'New York', 'London', 'Godda', 'Mumbai']
length = len(city_list)
print('Length of list = ',length)
      Length of list =  5

9. print(object): This function prints the object to the standard output device. For example:

# Printing a message onto the screen.
print('This is a message.')
      This is a message.

10. input(prompt): This function reads input, converts it to a string, and returns that. For example:

# Prompt or take the input from the user and store it into a variable str.
str = input('What is your name?')
      What is your name?

11. max(iterable): This function returns the largest number of two or more numbers. For example:

# Returns the largest number from the list.
num_list = [20, 40, 10, 60, 50, 30]
largest_num = max(num_list)
print('Largest number from list is ',largest_num)
      Largest number from list is  60

12. min(iterable): This function returns the smallest number of two or more numbers. For example:

# Returns the smallest number.
smallest_num = min(20, 10)
print('Smallest number is ',smallest_num)
      Smallest number is  10

13. range(stop) or range(start, stop): This function returns the sequence of numbers, starting from ‘start’ value up to (not including) the ‘stop’ value. For example:

# Creating a sequence of numbers from 0 to 7, and print each number in the sequence.
num = range(5)
for n in num:
    print(n, end=' ')
      0 1 2 3 4

14. round(f, n): This function rounds a number to a given precision in decimal digits. For example:

# Round a number to only two decimal points.
num = round(6.759, 2)
print(num) # Output: 6.76

15. log10(x): This function returns the logarithm of x at base 10. For example:

# Find the logarithm of a number at base 10.
import math
num = math.log10(2)
print(num) # Output: 0.301

Advantages of Functions in Python

There are the following advantages of functions in Python programming language. They are as:

  • Functions make the program development easy and fast.
  • They make the testing of program easy.
  • Code sharing is possible.
  • Functions increase the reusability of program code.
  • They increase the program readibility and understandability.

In this tutorial, you have learned about functions in Python with examples. Hope that you will have understood the basic points of functions and practiced all example programs.

In the next tutorial, we will discuss how to create a user-defined function, how to call a function in Python, return statement, etc.
Thanks for reading!!!

⇐ Prev Next ⇒

Please share your love