What is a function in Python

What is a function in Python?

In Python, function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes code reusable.

Syntax of Function

def function_name(parameters):
	"""docstring"""
	statement(s)
Above shown is a function definition which consists of following components.
  1. Keyword def marks the start of function header.
  2. A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in python.
  3. Parameters (arguments) through which we pass values to a function. They are optional.
  4. A colon (:) to mark the end of function header.
  5. Optional documentation string (docstring) to describe what the function does.
  6. One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces).
  7. An optional return statement to return a value from the function.

How to call a function in python?

Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters.
>>> greet('Paul')
Hello, Paul. Good morning!

Docstring

The first string after the function header is called the docstring and is short for documentation string. It is used to explain in brief, what a function does.
Although optional, documentation is a good programming practice. Unless you can remember what you had for dinner last week, always document your code.
In the above example, we have a docstring immediately below the function header. We generally use triple quotes so that docstring can extend up to multiple lines. This string is available to us as __doc__ attribute of the function.
For example:
Try running the following into the Python shell to see the output.
  1. >>> print(greet.__doc__)
  2. This function greets to
  3. the person passed into the
  4. name parameter

The return statement

The return statement is used to exit a function and go back to the place from where it was called.

Syntax of return

return [expression_list]
This statement can contain expression which gets evaluated and the value is returned. If there is no expression in the statement or the statement itself is not present inside a function, then the function will return the None object.
For example:
  1. >>> print(greet("May"))
  2. Hello, May. Good morning!
  3. None



Post a Comment

1 Comments