Creating a Function
Here are some basic principles for defining a function in Python:
- Function blocks start with the def keyword followed by the function name and parentheses ().
- You can place any arguments or input parameters should be placed within these parentheses. It can be blank also.
- The code within a function starts with a colon(:) and is always indented.
- The first statement of a function is optional - the function's documentation string or Docstring. A Docstring is a piece of information about what the function does. Docstring is optional, but it is good practice to provide docstring.
- The function body contains the code of the task the function is supposed to perform.
- The return [expression] statement terminates a function. A return statement without any arguments is the same as a return None.
We will talk about arguments and Docstring later in detail. So keep reading.
Syntax
def functionName( parameters ):
"function_docstring"
function_body
return [expression]
Example: Creating a Python Function
# A Python function.
def PythonFun():
print("Welcome to Coding Ninjas")
Also see, Python Filter Function
Calling a Function
After creating a function, we can call it by using its name followed by parenthesis containing its parameters. A function in Python can be called from another function, application, or directly from a Python prompt.
Example: Calling a Python Function
# A Python function.
def PythonFun(name):
print("Welcome to Coding Ninjas", name)
# Calling the above function.
PythonFun("Gazal")
Output
Welcome to Coding Ninjas Gazal
You can also read about the Multilevel Inheritance in Python.
Arguments of a Function
An argument is a value passed inside the parenthesis of the function. Any number of arguments separated by a comma can be passed to a function.
Python provides a variety of arguments that can be passed during a function call.
- Required arguments
- Default arguments
- Keyword arguments
- Variable-length arguments
Let's go over each one in detail.
Required Arguments
Required arguments are passed to a function in the correct positional order. In this case, the number of arguments in the function call should match the number of arguments in the function specification; otherwise, it will give a syntax error.
The example of required arguments is as follows:
# Python program to show default arguments.
def PythonFun(name):
print("Name: ", name)
# Function call
PythonFun('Gazal')
Output
Name: Gazal
Recommended Topic, Floor Division in Python
Default Arguments
A default argument is a parameter that takes on a default value if no value is specified in the function call. You can predefine some default values in the function so that the default value can be used whenever the value of that parameter is not provided.
The following example shows how to use Default parameters.
# Python program to show default arguments.
def PythonFun(name = "Gazal"):
print("Name: ", name)
# Function call
PythonFun()
Output
Name: Gazal
Note: Any number of parameters in a function can have a default value. However, once we have a default argument, all of the arguments to their right must also have default values.
Keyword Arguments
Here the caller can specify the argument name with values so that they do not need to remember the order of parameters.
The following example shows how to use Keyword parameters.
# Python program to show keyword arguments.
def Person(firstName, lastName):
print(firstName, lastName)
# Function Call
Person(firstName='Gazal', lastName = 'Arora' )
# Changing the order of parameters.
Person(lastName = 'Arora', firstName='Gazal')
Output
Gazal Arora
Gazal Arora
Variable-length Arguments
Python provides this unique variable-length Arguments functionality to pass a variable number of arguments using special symbols.
This is useful when you need to process a function for more arguments than you specified while defining the function.
There are two types of special symbols:
- **kwargs (Keyword Arguments)
- *args (Non-Keyword Arguments)
Example of *args
# Python function to show the use of *args
def PythonFun(*argv):
for words in argv:
print(words)
# Function Call
PythonFun('Welcome', 'to', 'Coding Ninjas')
Output
Welcome
to
Coding Ninjas
Example of **kwargs
# Python function to show the use of **kwargs
def PythonFun(**kwargs):
for key, val in kwargs.items():
print("%s = %s" % (key, val))
# Function Call
PythonFun(FirstName = 'Gazal', LastName = 'Arora')
Output
FirstName = Gazal
LastName = Arora
Docstring
The first string following the function is the Document string or Docstring. This is used to explain the function's functionality. Docstring in functions is optional; however, it is recommended.
Syntax to print the docstring of a function is:
print(function_name.__doc__)
The return statement
The function return statement is used to return/terminate from a function, go back to the function's caller, and return the specified data to the caller.
The return statement can be a variable, an expression, or a constant that is returned at the end of function execution. If nothing is sent in a return statement, a None object is returned.
# function to define docstring and return statement.
def length(string):
# docstring.
"""This function returns the length of the string passed"""
# returning a number.
return len(string)
print(length("Gazal"))
Python Function Pass by Reference vs pass by value
It's interesting to note that every variable name is a reference in Python. It means that if you modify what a parameter refers to within a function, the change is also reflected in the calling function. For example,
# function to show that parameters are passed by reference.
def pythonFun(myList):
myList[0] = 2
myList = [1, 2, 3]
print(myList)
pythonFun(myList)
print(myList)
Output
[1, 2, 3]
[2, 2, 3]
Here in the output, we can observe that the value of myList[0] was changed inside the pythonFun, but it is also changed in the main function. This proves passing by reference.
Anonymous Functions
An anonymous function in Python does not have a name. As previously stated, the def keyword is used to define normal functions, but the lambda keyword is used to define anonymous functions. For example,
# function to show anonymous functions
def square(x): return x*x
# anonymous function
square_2 = lambda x : x*x
print(square(2))
print(square_2(2))
Output
4
4
You can practice by yourself with the help of online python compiler.
Frequently Asked Questions
How many types of functions are there in Python?
There are mainly two kinds of functions. User-defined functions and Built-in functions. User-defined functions are those that the user defines to fulfill a specified purpose. Built-in functions are those that are predefined in Python.
What is the formula for function?
In Python, a function is defined using the syntax def function_name(parameters):, followed by an indented block of code that performs the desired task.
What are the five functions in Python?
Five common Python functions include print(), len(), type(), max(), and min(). These built-in functions help with output, data manipulation, and obtaining information about variables.
Conclusion
In conclusion, Functions in Python are fundamental to writing clean, efficient, and modular code. They enable you to break down complex problems into manageable tasks, promote code reuse, and enhance readability. By mastering the use of functions, you can create more organized and maintainable programs, ultimately becoming a more proficient and effective Python developer.
Check out this article - Quicksort Python
Recommended Readings: