Python Functions Example | Python def Tutorial
Python Functions Example | Python def Tutorial is the topic, we will discuss today. In this article, you’ll learn about Python functions; what is a function in Python, the syntax, components, and types of the functions. Also, you’ll learn to create the function in Python. A function in any programming language is a block of organized, reusable code that is used to perform the single, related action. Functions provide better modularity for our application and code reusability.
Python Functions Example
What is a function in Python? In Python, a function is the group of related statements that perform the specific task. Functions help us to break our program into smaller and modular pieces. As our program grows larger and larger, the functions make it more organized, manageable, and reusable. Furthermore, it avoids repetition and makes code reusable.
Syntax of Function in Python
def function_name(parameters): """docstring""" statement(s)
Above shown is the function definition which consists of the following components.
- Keyword def marks the start of the function header.
- Provide a function name to identify that function uniquely. Function naming follows the same conventions of writing the identifiers in the Python language.
- Parameters (arguments) are optional through which we pass values to the function.
- The colon (:) to mark the end of the function header.
- Optional documentation string or docstrings to describe what the function does in the program. It is a comment in the programming language.
- Function body contains one or more valid python statements. Statements must have the same indentation level (usually four spaces).
- The optional return statement to return the value from the function.
By default, the parameters have a positional behavior, and you need to inform them in the same order as they were defined.
Example of Functions in Python
See the following example of Function body.
def GoT(char): """This function print chars to""" print(char) return
How to call a function in python?
Defining the function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.
Once you have defined the basic structure of Python, then you can either execute it by the calling it from another function or directly from the Python prompt.
If we want to call the function, we type the function name with appropriate parameters. See the full code below.
# app.py def GoT(char): """This function print chars to""" print(char) return GoT("Jon snow")
The output is following.
Pass by value vs. Pass by reference
All the parameters (arguments) in the Python language are passed by reference. It means that if you change what the parameter refers to within the function, the change also reflects in the calling function. See the below code.
# app.py def apps(list): list.append(21) print("Values inside the function: ", list) return list = ['Facebook', 'Instagram', 'Messenager'] apps(list) print("Values outside the function: ", list)
So, here we are modifying the list inside the function and see if the outside function list is changed or not. See the below output.
So, in the above code, we are appending one item 21 inside the function and still outside list is updated that means it is passed by reference.
There is one more example where an argument is being passed by reference, and the reference is being overwritten inside the called function. See the following code.
# app.py def apps(list): list =  print("Values inside the function: ", list) return list = ['Facebook', 'Instagram', 'Messenager'] apps(list) print("Values outside the function: ", list)
The output is following.
The parameter list is local to the function apps. We are not modifying the existing list; we are assigning the new list that is why changing the list within the function does not affect the list. The function accomplishes nothing.
Docstring in Python
The first string after the function header is called a docstring and is the short for documentation string. Docstring used to explain in brief, what the function does. If you are familiar with Laravel, then it might be a familiar term to you.
Although they are optional, proper documentation counts as a best programming practice. Unless you can remember what you had done with your code a month ago, otherwise always document your code.
The return statement
The return statement is used to exit the function and go back to the place from where it was called. The syntax of the return statement is following.
The return statement can contain an expression which gets evaluated, and the value is returned. If there is no expression in a statement or the return statement itself is not present inside the function, then a function will return the None object.
Scope and Lifetime of variables
The scope of the variable determines the portion of a program where you can access the particular identifier. There are two necessary scopes of variables in Python which are following.
- Global variables
- Local variables
Scope of the variable is the portion of a program where the variable is recognized. Parameters and variables defined inside the function are not visible from the outside world. Hence, they have the local scope.
A lifetime of a variable is the period throughout which the variable exists in the memory. The lifetime of variables inside the function is as long as the function executes.
All the variables in the program may not be accessible at all the locations in that program. It depends on where you have declared the variable.
Variables are destroyed once we return from the function. Hence, the function does not remember any value of a variable from its previous calls. See the following code for example.
# app.py def movie(): endgame = 10 print("Value inside function:", endgame) endgame = 20 movie() print("Value outside function:", endgame)
You can call the function by using following types of formal arguments.
- Required arguments.
- Keyword arguments.
- Default arguments.
- Variable-length arguments.
The Anonymous or Lambda Functions
Lambda Functions are called anonymous because they are not declared conventionally by using a def keyword. You can use the lambda keyword to create small anonymous functions.
Lambda forms can take any number of arguments but return just one value in the form of expression. They cannot contain any commands or multiple expressions.
- An anonymous function cannot be the direct call to print because lambda requires an expression.
- Lambda functions have their local namespace and cannot access the variables other than those in their parameter list and those in the global namespace.
Although it appears that lambda functions are the one-line version of the function, they are not equivalent to the inline statements in C or C++, whose purpose is bypassing function stack allocation during the invocation for performance reasons.
Conclusively, Python Functions Example | Python def Tutorial is over.