Python Functions Tutorial with Examples

In Python, a function represents a collection of statements designed to execute a specific operation. The primary concept behind this is to consolidate tasks that we frequently perform into one coherent function. By doing so, we can conveniently invoke the function whenever required, allowing us to reuse the code effectively without the necessity of rewriting identical code for various inputs.

Advantages of Using Functions in Python

The following are some of the key benefits of using Python Functions

  • Functions help in the reusability of code.
  • It also reduces the code length.
  • It improves the readability of code.
  • Declaration of Python Function

In Python, a function is declared using the following syntax:

Types of Functions in Python

The subsequent categories of functions utilized in Python are as follows:

  • Built-in Functions: These are standard functions provided by Python that are readily available for use at any moment.
  • User-defined Functions: These functions are constructed by users according to their specific needs and preferences.
  • Creating a Function in Python

In Python, functions are created utilizing the def keyword. We can incorporate various functionalities and attributes into these functions according to our requirements.

Below is an illustration demonstrating how to define a function in Python:

Example

# Simple example to write a function

# using def keyword to define a function

def welcome():

  print("Hello, Users! Welcome to our tutorial!!")

Explanation:

In this instance, we utilized the keyword def to create a function. The name of this function is welcome. Within the body of this function, we have included a segment of code designed to output a greeting message for the users.

Calling a Function in Python

After defining a function in Python, it can be invoked by using the function's name along with parentheses. These parentheses contain any arguments that are applicable for the particular function.

Below is an illustration demonstrating the process of invoking a Python function:

Example

Example

# Simple example to write a function

# using def keyword to define a function

def welcome():

  print("Hello, Users! Welcome to our tutorial!!")

# calling of the defined function

welcome()

Output:

Output

Hello, Users! Welcome to our tutorial!!

Explanation:

In this instance, we invoked the defined function welcome by utilizing the function's name succeeded by parentheses. We did not include any arguments, since the function itself does not necessitate any parameters in this particular scenario.

Python Function Arguments

In Python, function arguments refer to the values that are supplied to a function during its invocation. These values are utilized by the function to execute its tasks effectively.

Here is an example of Python Function Arguments:

Example

Example

# Simple example to write a function

# using def keyword to define a function

def welcome(name): # <--- parameter

  print(f"Hello, {name}! Welcome to our tutorial!!")

# calling of the defined function

welcome("John") # <--- argument

Output:

Output

Hello, John! Welcome to our tutorial!!

Explanation:

In this illustration, we established a function named welcome(name), with 'name' serving as the string parameter situated within the parentheses. Within the body of this function, we output a welcome message. Subsequently, we invoked the function by supplying an argument to it.

Let us see another example:

Example

Example

# Simple Python Program to add two numbers

# defining a function to add two numbers

def addition(num1, num2): # <- 2 parameters (num1, num2)

  # storing the sum of the numbers

  sum = num1 + num2

  # printing the result

  print(num1, "+", num2, "=", sum)

# calling the function

addition(18, 15)  # <- passing 18 and 15 as arguments to the function

Output:

Output

18 + 15 = 33

Explanation:

In the preceding illustration, we established a function named addition that takes two arguments - num1 and num2. Within this function, we computed the total of these numbers and subsequently displayed the result.

Beyond the scope of the function, we invoked the function by supplying the values 18 and 15 as its parameters.

Types of Python Function Arguments

There are several types of function arguments:

  • Positional Arguments
  • Keyword Arguments
  • Default Arguments
  • Arbitrary Arguments (Variable-length arguments args and *kwargs)
  • Python Return Statement

In Python, the return statement serves the purpose of sending a value back from a function.

Let us take a look at the following example:

Example

Example

# defining a function

def squareOf(num):

  res = num ** 2

  return res  # using return statement

# function call

sqr = squareOf(13)

# printing the result

print("Square of 13:", sqr)

Output:

Output

Square of 13: 169

Explanation:

In the preceding illustration, we defined a function named squareOf. This particular function takes a numeric value as its parameter and produces the square of that specified number as its output.

Consequently, when we supply the value 13 to the function, it yields its square, which is 169. We then assign this returned result to a variable and output it for visualization.

Note: The return statement also indicates that the function has ended. Any code written after the return statement does not execute.

Python Pass Statement

The pass statement serves as a stand-in for code that will be implemented later. By utilizing this, we can avoid issues arising from unpopulated code sections. Typically, it is employed in situations where the logic is intended but has not been fully developed.

Let us see an example:

Example

Example

# defining a function

def function_name():

  pass  # using pass as placeholder

# calling the function

function_name()

Explanation:

In this illustration, the pass statement is employed within the function. This pass statement serves as a placeholder for a code block that will be implemented in the future. When we invoke the function, it will execute without generating any errors.

Conclusion

Functions serve as the fundamental components of any programming language. In Python, they are utilized to construct clear, reusable, and efficient code. Whether you opt for built-in functions or design your own custom functions, they enable developers to consolidate logic into a singular block, thereby improving code readability, user-friendliness, and simplifying the processes of debugging or extending functionality. Ranging from basic parameter management to more complex topics such as recursion, anonymous (lambda) functions, nested functions, and variable-length arguments (args and *kwargs), functions play a crucial role in crafting scalable and maintainable Python applications. Mastery of Python functions will significantly enhance your problem-solving capabilities.

Python Functions FAQs

1. What is a function in Python?

A function in Python constitutes a series of statements that execute a specific operation. It is created by utilizing the def keyword and is invoked as required.

2. What are the benefits of functions in Python?

Functions are beneficial as they promote:

  • Code reusability
  • Reduced code repetition
  • Improved readability
  • Better modularity and debugging
  • 3. What is the difference between are *args and **kwargs?

*args **kwargs
The *args is used to pass a variable number of non-keyword arguments in Python functions. The **kwargs is used to pass a variable number of keyword arguments in Python functions.

Input Required

This code uses input(). Please provide values below: