Functions in Python
Functions are used to group a certain number of related instructions. These are reusable blocks of codes written to carry out a specific task. A function might or might not require inputs. Functions are only executed when they are specifically called. Depending on the task a function is supposed to carry out, it might or might not return a value.
Watch this video on ‘Python Functions’:
In this module, we will learn all about functions in Python to get started with them. Following is the list of topics we will cover in this module.
So, without any further delay, let’s get started.
What Is a Function in Python?
Functions in Python are a set of related statements grouped to carry out a specific task. Including functions in our program helps in making it much more organized and manageable. Especially, if we are working on a large program, having smaller and modular chunks of code blocks will increase the readability of the code along with providing it reusability.
There are three types of functions:
- Python Built-in functions (an already created, or predefined, function)
- User-defined function (a function created by users as per the requirements)
- An anonymous function (a function having no name)
Defining a Function in Python
While defining a function in Python, we need to follow the below set of rules:
- The def keyword is used to start the function definition.
- The def keyword is followed by a function-name which is followed by parentheses containing the arguments passed by the user and a colon at the end.
- After adding the colon, the body of the function starts with an indented block in a new line.
- The return statement sends a result object back to the caller. A return statement with no argument is equivalent to a return none statement.
The syntax for writing a function in Python:
def (arg1, arg2, … argN):
return
Calling a Function In Python
Defining a function is not all we have to do to start using it in our program. Defining a function only structures the code blocks and gives the function a name. To execute a function, we have to call it. Only when it is specifically called, a function will execute and give the required output. Now, there are two ways in which we can call a function after we have defined it. We can either call it from another function or we can call it from the Python prompt.
Get 100% Hike!
Master Most in Demand Skills Now!
Example:
# defining a function
def printOutput( str):
#This function will print the passed string
print (str)
return;
#calling a function
printOutput(“Welcome to Intellipaat”)
Output:
Welcome to Intellipaat
Adding a Docstring in a Python Functions
The first statement or string in any Python function (optional statement) is called a docstring. It is used to briefly and crisply describe what a function does. ‘Docstring’ is the abbreviation for ‘documentation string’.
Even though including a docstring in our function is optional, it is considered a good practice as it increases the readability of the code and makes it easy to understand. We use triple quotes around the string to write a docstring. A docstring can also extend up to multiple lines.
Example:
In the example provided for calling a function, we used a comment to describe what the function was going to do. We will do the same in this example as well. Only that, we will use a docstring here to describe what the function will do.
# defining a function
def printOutput( str):
“’This function will print the passed string’”
print (str)
return;
#calling a function
printOutput(“Welcome to Intellipaat”)
Output:
Welcome to Intellipaat
Scope of Variables in Python Functions:
The scope of a variable is a part of the program where the variable is recognizable.
As we have already discussed local and global variables in the Python Variables module of this tutorial, we know that the variables defined inside a function only have a local scope. Meaning, the variable defined within a function is only recognizable inside that function.
The lifetime of a variable is the time period till the variable exists in the memory. Variables defined inside the function only exist as long as the function is being executed. So, the lifetime of a variable defined inside a function ends when we return from the function or when the control comes out of the function.
Example with variables in Python Functions:
def func():
x = 5
print(“value of x inside the function”, x)
#calling the function
x = 10
func()
print(“value of x outside the function”, x)
Output:
value of x inside the function 5
value of x outside the function 10
Main Function in Python
In any program, the main() function is like the entry point. But as we already know, the Python interpreter runs the code right from the very first line and then goes line by line. It does not matter if the main function is present or not.
Since there is no main() function in Python, when a Python program is run, the code present at level 0 indentation is executed. However, before doing that, a few special variables are defined. __name__ is one such special variable. If the source file is executed as the main program, the interpreter sets the __name__ variable to have a value __main__. If this file is being imported from another module, __name__ will be set to the module’s name.
print("Hello")
def main():
print("Hey There")
if __name__=="__main__":
main()
When this program is executed, the interpreter declares the initial value of the name as “main”. When the interpreter reaches the if statement it checks for the value of the name and when the value of it is true it runs the main function else the main function is not executed.
This brings us to the end of this module in Python Tutorial. Here we have learned what function is with the help of a few Python function examples. Now, if you are interested to know why python is the most commonly used language for data science, you can go through this Python Data Science tutorial.
For getting certified and having the best career growth, check out our Python training course. Also, Intellipaat is providing free Python interview questions for freshers, which will help you excel in your career.