Skip to content

Definition and Use

In Python, a function is a reusable block of code that performs a specific task. It is defined using the keyword def, followed by the function name, parameters (optional), and the code block to be executed. Functions can receive input data (arguments) and return output data (values).

  • Code organization: Functions divide the code into smaller and more manageable blocks, making it more readable and easier to understand.

  • Reuse: They allow you to reuse the same code in different parts of the program without having to rewrite it.

  • Modularity: Facilitates the creation of complex programs by allowing the construction of independent code blocks that can be combined.

  • Facilitates debugging: Functions help isolate problems and find errors more efficiently.

To define a function in Python, the following syntax is used:

function.py
def function_name(optional_arguments):
# Code block to execute
# ...
return return_value (optional)
  • def : Keyword that indicates that a function is being defined.

  • function_name : Name given to the function in order to call it later.

  • optional_arguments : Parameters that the function receives as input. There can be zero, one, or several.

  • #Code block to execute : The code that will be executed when the function is called. return: Optional. The return statement allows the function to return a value to the part of the program that called it. If return is not included, the function returns None.

greet.py
def greet():
# Code block to execute
greeting = 'Hello PyDocs'
return greeting
# Call function
greet()

Output:

greet.py
Hello PyDocs