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.
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:
Rules for naming python function (identifier)
It can begin with either of the following: A-Z, a-z, and underscore(_).
The rest of it can contain either of the following: A-Z, a-z, digits(0-9), and underscore(_).
A reserved keyword may not be chosen as an identifier.
It is good practice to name a Python function according to what it does.
Python Function Parameters
Sometimes, you may want a function to operate on some variables, and produce a result. Such a function may take any number of parameters. Let’s take a function to add two numbers.
Example:
Python return statement
A Python function may optionally return a value. This value can be a result that it produced on its execution. Or it can be something you specify- an expression or a value.
Example:
No comments:
Post a Comment