Python Functions

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

Example

 
def my_function():
  print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

Example

 
def my_function():
  print("Hello from a function")


<strong>my_function()</strong>

Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:

Example

 
def my_function(<strong>fname</strong>):
  print(fname + " Refsnes")


  my_function(<strong>"Emil"</strong>)
my_function(<strong>"Tobias"</strong>)
my_function(<strong>"Linus"</strong>)

Arguments are often shortened to args in Python documentations.

Parameters or Arguments?

The terms parameter and argument can be used for the same thing: information that are passed into a function.

Python Functions

A function in Python is an aggregation of related statements designed to perform a computational, logical, or evaluative task. The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can call the function to reuse code contained in it over and over again. 

Functions can be both built-in or user-defined. It helps the program to be concise, non-repetitive, and organized.

Syntax: 

 def function_name(parameters):
    """docstring"""
    statement(s)

Example:

 even
odd

Docstring

The first string after the function is called the Document string or Docstring in short. This is used to describe the functionality of the function. The use of docstring in functions is optional but it is considered a good practice.

The below syntax can be used to print out the docstring of a function:

 Syntax: print(function_name.__doc__)

Example:

 defsay_Hi():
    "Hello! geeks!"
  
  
print(say_Hi.__doc__)

Output:

 Hello! geeks!

The return statement

The return statement is used to exit from a function and go back to the function caller and return the specified value or data item to the caller.

 Syntax: return [expression_list]

For more, checkout W3Schools and Geeks For Geeks.