This article will teach you about functions, including what they are, their syntax, components, and types. You’ll also learn how to write a Python function.
What is a function in Python?
A function in Python is a collection of connected statements that performs a single task.
Functions assist in the division of our software into smaller, modular portions. Functions help our program become more ordered and controllable as it grows in size.
Furthermore, it avoids repetition and makes the code reusable.
Syntax of Function
def function_name(parameters): """docstring""" statement(s)
Above shown is a function definition that consists of the following components.
- The start of the function header is indicated by the keyword def.
- A name for the function that can be used to distinguish it from others. The same criteria apply to naming functions as they do to naming identifiers in Python.
- We pass values to a function using parameters (arguments). They aren’t required.
- The function header is terminated by a colon (:).
- Documentation string (docstring) that can be used to describe what the function does.
- The function body is made up of one or more valid Python statements. The indentation level of all statements must be the same (usually 4 spaces).
- A return statement can be used to return a value from a function.
Example of a function
def greet(name): """ This function greets to the person passed in as a parameter """ print("Hello, " + name + ". Good morning!")
How to call a function in python?
We can call a function from another function, a program, or even the Python prompt once we’ve declared it. We just type the function name followed by the relevant parameters to call it.
>>> greet('Paul') Hello, Paul. Good morning!
Try running the above code in the Python program with the function definition to see the output.
def greet(name): """ This function greets to the person passed in as a parameter """ print("Hello, " + name + ". Good morning!") greet('Paul')
Note: The function definition must always be present before the function call in Python. We’ll get an error if we don’t. As an example,
# function call greet('Paul') # function definition def greet(name): """ This function greets to the person passed in as a parameter """ print("Hello, " + name + ". Good morning!") # Erro: name 'greet' is not defined
The Document string, or Docstring in short, is the first string after the function. This is used to describe a function’s functionality. The usage of docstring in functions is not required, however it is recommended.
The following syntax can be used to print a function’s docstring:
Try running the following into the Python shell to see the output.
>>> print(greet.__doc__) This function greets to the person passed in as a parameter
The return statement
To quit a function and return to its original position, use the return statement.
Syntax of return
This statement may include an expression that will be evaluated and the result returned. The function will return the None object if there is no expression in the statement or if the return statement is not present inside the function.
>>> print(greet("Rocky")) Hello, May. Good morning! None
If greet() prints the name without using a return statement, the returned result is None.
Example of return
def absolute_value(num): """This function returns the absolute value of the entered number""" if num >= 0: return num else: return -num print(absolute_value(2)) print(absolute_value(-4))
How Function works in Python?
Scope of Variables
It’s possible that not all variables in a program are available at all times. This is determined by where you declared a variable.
The scope of a variable controls where in the program a specific identifier can be accessed. In Python, there are two fundamental types of variable scopes.
- Global variables
- Local variables
Global vs. Local variables
Variables specified inside a function body have a local scope, while variables defined outside the function body have a global scope.
Local variables can only be accessed within the function in which they are defined, whereas global variables can be accessed by all functions throughout the program body. The variables declared inside a function are brought into scope when you call it. A simple example is shown below.
#!/usr/bin/python total = 0; # This is global variable. # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2; # Here total is local variable. print "Inside the function local total : ", total return total; # Now you can call sum function sum( 10, 20 ); print "Outside the function global total : ", total
When the above code is executed, it produces the following result −
Inside the function local total : 30 Outside the function global total : 0