Python Functions:
A function is a block of code that is written once and can be executed whenever required in the program, to produce some output.
Types of Functions:
Built-in Functions:
The Python library already contains some functions that are predefined to perform a specific function. These functions are known as built-in functions.
User- Defined Functions:
Functions are often created by user itself within the code to simplify the code and to increase the code reusability. Such user created functions for code simplification are called as user-defined functions.
Creating a Python Function:
Creating or defining a python function is done by using the def keyword.
Syntax:
def function_name(parameters):
Statements
Calling a Python Function:
Writing the function name followed by parenthesis serves the purpose of function calling in Python.
Syntax:
def function_name(parameters):
Statements
function_name()
Parameters in a Python Function:
The information passed in the function definition are called as parameters. Parameters are variable in nature and can often called as formal parameters or formal arguments.
Arguments in a Python Function:
The information passed in the function call are called as arguments. Arguments be taken as literals, variables and expressions and they are often called as actual parameters or actual arguments.
Scope of a Variable in/out a Python Function:
The part of the code where a variable is accessible within the code is called as the scope of the variable.
Types of Scope of a Python Variable:
Python Local Variables:
A Local Variable is accessible only inside the function body, as it is declared inside a function body and thus have a local access only.
Python Global Variable
A Global Variable is accessible all over the program code as it is declared outside a function body and thus have a global access.
Example:
def expression(x): return 10*(x+20) print(expression(10)) print(expression(20)) print(expression(30)) |
Output: