How To Add Functions In Python

In this tutorial, we will learn how to add functions in Python. Functions are essential building blocks in any programming language, and Python is no exception. Python functions help you organize your code, reduce repetition, and make it more readable and reusable.

What are functions in Python?

A function is a block of organized, reusable code that can be used to perform a single, related task. Functions provide better modularity, reuse, and manageability of code. In Python, you can define functions using the def keyword, followed by the function name and a pair of parentheses containing any input parameters the function may have.

Now, let’s dive into creating and using functions in Python.

Step 1: Define a function using ‘def’

To define a function, use the def keyword followed by the function name and a pair of parentheses for input parameters. The function body should be indented (use 4 spaces for each level of indentation), and it is recommended to add a docstring (triple-quoted multiline string) at the beginning of your function to explain its purpose and usage.

Step 2: Call the function by its name

To use the function you defined, simply call it by its name followed by a pair of parentheses.

Step 3: Add input parameters to your function

You can define input parameters for your function by placing them inside the parentheses after the function name. Multiple parameters should be separated by commas.

Step 4: Add a return statement to your function

The return statement allows your function to return a value that can be assigned to a variable or used in an expression. If your function doesn’t have a return statement, it will return None by default.

Step 5: Set default parameter values

You can assign default values to your function’s parameters, which will be used if the caller doesn’t provide a value for that parameter. To do this, simply add an equals sign (=) followed by the default value after the parameter name.

Full code example


Hello, John! Welcome to the Python functions tutorial!


In this tutorial, we learned how to add functions in Python. By defining and using functions, you can make your code more organized and reusable. Additionally, functions make it easier to understand the purpose, input parameters, and return values for specific pieces of code, making your program more readable and maintainable. Happy coding!