Python Function – Example & Syntax

Tutorial Playlist

Python Functions help organize code and make them reusable. Instead of rewriting the instructions repeatedly, you define a function once and use it whenever necessary. This improves readability, reduces duplication, and keeps the code structured. Functions break extensive work into simpler and more workable units, which makes it simpler to handle the code. Using functions can help you save time and reduce errors in the program. In this article, you will explore different ways to use functions in Python with detailed examples for each.

Table of Contents:

What is a Function in Python?

The Python language provides functions as a method to bundle related lines of code that complete particular assignments. Functions allow us to conserve programming code from duplication by storing it as reusable blocks for later use.  When working on a large program, breaking it into smaller functions helps to keep the code clean and improve readability. It also makes the program reusable, which prevents repeating the logic several times. Functions also help in debugging by finding and fixing errors.

Why Use Functions in Python?

Functions in Python assist in making the code better organized, reusable, and simpler to handle. Rather than typing the same code repeatedly, we can create a function and call it whenever required. This enhances readability, reduces errors, and makes debugging easier.

Become the Go-To Expert in Python Programming
Unlock Python Programming Mastery Here
quiz-icon

Advantages of Using Functions in Python

  • Code Reusability: Write once and reuse many times without typing the same logic.
  • Organizing the code: The bigger program is divided into multiple parts using a function that helps in the easy handling of the program.
  • Better Readability: It helps in keeping the code organized, which makes it easier to read.
  • Easy Debugging: It helps debug in a particular location and access the error throughout the entire program
  • Improves Collaboration: It helps several programmers to combine and work on various functions at the same time without disturbing others.

Types of Functions in Python

Python functions are mainly classified into two types:

Built-in Functions in Python

Built-in functions are the predefined functions that come integrated with Python. They are readily available for use, and there is no need for the user to define them again and they can be used directly.

Most Commonly Used Built-in Functions in Python

  1. len() Function in Python

The len() function in Python helps in getting the length of any type of data, like a string, list, or tuple. The len() function is used to get the length (number of elements) of an object like a string, list, dictionary, or set.

Example 1:

Python

Output:

len() Function in Python Output

Explanation: Here, the len() returns the total number of characters in the course name. It even considers the spaces.

  1. max() Function in Python

The max() function returns the largest item in an iterable (like a list, or tuple) or among multiple numbers given as arguments.

Example 1:

Python

Output:

max() Function in Python Output

Explanation: Here, the highest number in the list is returned using the max() function.

Example 2:

Python

Output:

max() Function in Python Example Output

Explanation: Here, max() returns the character that appears last in alphabetical order based on ASCII values.

  1. sum() Function in Python

The sum() function in Python helps in adding all the elements in the list or tuple and returns their total.

Example 1:

Python
 

Output:

sum() Function in Python Output

Explanation: Here, sum() adds all numbers in the list and returns the total.

Example 2:

Python
 

Output:

sum() Function in Python Example

Explanation: Here, sum() calculates the total ASCII value of all characters in the string.

  1. round() Function in Python

The round() function rounds off a floating-point number to a specified number of decimal places.

Example 1:

Python
 

Output:

round() Function in Python Output

Explanation: Here, round() rounds off the number to 2 decimal places.

Example 2:

Python

Output:

round() Function in Python example

Explanation: Here, round() rounds the result of dividing the length of the course name by 10 to one decimal place..

  1. type() Function in Python

The type() function returns the data type of a given object.

Example 1:

Python

Output:

type() Function in Python

Explanation: Here, type() returns the data type of the variable.

Example 2:

Python
 

Output:

type() Function in Python Example

Explanation: Here, type() returns the string data type as the string data is defined as the course input.

Stay Ahead in the World of DS and AI
Learn How Artificial Intelligence is Revolutionizing Data Science Practices
quiz-icon

User-defined Functions in Python

User-defined functions are defined by the users in Python to perform particular tasks.

  1. Function to Add Two Numbers

This function takes two numbers as input, adds them, and returns the result.

Example:

Python

Output:

Function to Add Two Numbers

Explanation: Here, add_numbers() adds the two numbers given as input and returns the sum as a result.

  1. Function to Check Even or Odd

This function checks whether a given number is even or odd using the modulus operator %.

Example:

Python

Output:

Function to Check Even or Odd Output

Explanation: Here, check_even_odd() checks whether a number is even or odd based on the modulus operator.

  1. Function to Find Factorial

A function that calculates the factorial of a number using a loop. The factorial of n is the product of all positive integers up to n.

Example:

Python

Output:

Function to Find Factorial

Explanation: Here, the factorial() function calculates the product of all numbers from 1 to n using a loop

  1. Function to Reverse a String

This function takes a string as input and returns its reverse using slicing ([::-1]).

Example:

Python

Output:

Function to Reverse a String

Explanation: Here, [::-1] returns the reverse of the string intellipaat.

  1. Function to Find the Square of a Number

This function takes a number as input and returns its square using multiplication (num * num).

Example:

Python

Output:

Function to Find the Square of a Number

Explanation: Here, the * operator is defined by the user to find the square of the number.

Defining a Function in Python

While defining a function in Python, we need to follow the below set of rules:

  • The def keyword is used to start the function definition.
  • The def keyword is followed by a function name and parentheses containing the arguments passed by the user and a colon at the end.
  • After adding the colon (‘:’), the body of the function starts with an indented block in a new line.
  • The return statement sends a result object back to the caller. A return statement with no argument is equivalent to a return none statement.

The syntax for defining a function in Python:

<br>
def function_name(arg1, arg2, … argN):
return value

Example:

Python

Output:

defining a function in Python Output

Explanation: Here, the function takes a course name and duration as input and returns a simple message about the course.

Calling a Function in Python

Defining a function is not all we have to do to start using it in our program. Defining a function only structures the code blocks and gives the function a name. To execute a function, we have to call it. Only when it is specifically called, a function will execute and give the required output. Now, there are two ways in which we can call a function after we have defined it. We can either call it from another function or we can call it from the Python prompt.

The syntax for calling a function in Python:

function_name(argument1, argument2, … argumentN)
return

Example:

Python

Output:

calling a function in Python output

Explanation: Here, the function takes a course name as input and prints on calling it.

Get 100% Hike!

Master Most in Demand Skills Now!

Adding a Docstring to a Python Function

The first statement or string in any Python function (optional statement) is called a docstring. It is used to briefly and crisply describe what a function does. ‘Docstring’ is the abbreviation for ‘documentation string’.

Even though including a docstring in our function is optional, it is considered a good practice as it increases the readability of the code and makes it easy to understand. We use triple quotes around the string to write a docstring. A docstring can also extend up to multiple lines.

Syntax for adding a docstring in a function:

def function_name():
  """This function performs a specific task"""
# Function body
pass  # Placeholder statement (replace with actual code)
return

Example:
Python

Output:

docstring in a function

Explanation: Here, the docstring is used to explain what the function does. A docstring is a special type of comment written inside triple quotes (“””) instead of using the regular comment’#’. It helps to easily read the code and understand the purpose of the function.

Python Function Arguments

Arguments are values that are passed inside the parentheses of a function. Python functions can accept multiple arguments, which are separated by commas.

Example:

Python

Output:

Python Function Arguments Output

Explanation: Here, the function checks whether a number is even or odd by using the modulus operator. Here,15 and 10 are passed as arguments to check whether they are odd.

There are four types of function arguments in Python:

  • Default Arguments
  • Keyword Arguments
  • Positional Arguments
  • Arbitrary Arguments

1. Default Arguments

When an argument is not provided in the function call, a default value is used, which is specified in the definition of the function itself.

Example:

Python

Output:

Default Arguments

Explanation: Here, we define a function with a default value for the duration argument. Since no value is provided, the default value of 6 months is used.

2. Keyword Arguments

The keyword argument allows to give the values to a function with the name, so the order does not matter.

Example:

Python

Output:

Keyword Arguments

Explanation: Here, the function arguments are specified  by name, allowing us to pass them

3. Positional Arguments

The order of arguments is important in positional arguments. This means the first value is assigned to the first parameter, the second value to the second parameter, and so on.

Example:

Python

Output:

Positional Arguments

Explanation: Here, the order of arguments is important and affects function execution. In the correct order, the name is assigned the value “Rahul” and the experience value is 10. In the incorrect order, the values are swapped, causing incorrect output.

4. Arbitrary Arguments

The arbitrary arguments allow a function to accept multiple arguments, which flexibility to handle different amounts of data.

Example:

Python

Output:

Arbitrary Arguments

Explanation: Here, we handle multiple arguments dynamically using *args to accept variable-length inputs.

Scope of Using Variables in Python Functions

The scope of a variable is the part of the program where the variable is recognizable.
As we have already discussed local and global variables in the Python Variables module of this tutorial, we know that the variables defined inside a function only have a local scope. Meaning that the variable defined within a function is only recognizable inside that function.

The lifetime of a variable is the period during which the variable exists in memory. Variables defined inside the function only exist as long as the function is being executed. So, a variable inside a function exists only while the function runs. After the function ends, the variable is removed.

Example:

Python

Output:

Scope of Using Variables in Python Functions

Explanation: Here, the function func() has a local x = 5, which exists only inside it. When called, it prints x as 5, while the global x = 10 remains unchanged outside, showing the variable scope

Main Function in Python

In any program, the main() function is like the entry point. But as we already know, the Python interpreter runs the code right from the very first line and then goes line by line. It doesn’t matter if the main function is present or not.

Since there is no main() function in Python, when a Python program is run, the code present at level 0 indentation is executed. However, before doing that, a few special variables are defined. __name__ is one such special variable. If the source file is executed as the main program, the interpreter sets the __name__ variable to have a value __main__. If this file is being imported from another module, __name__ will be set to the module’s name.

Example:

Python

Output:

Main Function in Python

Explanation: Here, when the program is executed, the interpreter declares the initial value of the name as “main”. The interpreter sets __name__ to __main__ when the script is executed directly, which allows the main() function to run only in that case.

Best Practices When Using Functions in Python

  1. Keep It Simple: Write one-task-per-function function. When a function is too long or complicated, split it into simpler functions for readability.
  2. Use Descriptive Names: Names of functions should describe the action they perform, making the code more readable.
  3. Avoid Global Variables: Using too many globals can complicate debugging. Pass values in as function arguments whenever possible.
  4. Use Default Arguments Wisely: Provide default values to the parameters when possible to make the function more efficient and convenient.
  5. Keep Functions Modular: Each function should be independent and reusable, to make it easier to manage and debug.
  6. Handle Edge Cases: Handle extreme inputs such as empty lists, zero values, or extremely large numbers when coding functions.

Conclusion

Python functions enable users to code in such a way that the code becomes reusable, well-structured, and easier to debug. Functions divide a lengthy task into small pieces that can be managed easily. It also enables you to reduce redundancy. The use of default arguments and lambda functions is very helpful and is an effective programming feature. Knowing how to write and use functions is essential for a coding professional to write clean code.

To take your skills to the next level, enroll in our Python training course and gain hands-on experience. Also, prepare for job interviews with our Python interview questions, prepared by industry experts.

Functions in Python - FAQs
1. Why are functions important in Python?

Functions make code reusable, organized, and easier to debug.

2. What are the four types of functions in Python?

Python contains native built-in functions as well as user-defined functions, anonymous (lambda) functions, and recursive functions.

3. What is a user-defined function in Python?

A function created by the users using def to perform a specific task.

4. Why are functions important in Python?

Functions make code reusable, organized, and easier to debug.

5. What are the two main types of functions in Python?

Python has two types of functions –  built-in functions (like print()) and user-defined functions (created with def).

6. How many functions are there in Python?

Python includes more than 60 built-in functions, and users can generate infinite user-defined functions.

Our Python Courses Duration and Fees

Program Name
Start Date
Fees
Cohort Starts on: 19th Apr 2025
₹20,007

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.