In the beginning , I will just say when you divide your code into , smaller blocks which performs an specific task . You can also call anytime in your code to avoid repetitions of writing code . These are functions . The Functions in Python programming language are the most important part. I mean not only for python but it is true with other programming languages .If you really want to become a python expert programmer , Function’s hands on knowledge is compulsory. This article will provide you A-Z information about functions in programming .
There are so many built in functions provided by Python Interpreter which you must know . These inbuilt functions in python simplifies the task for you . For example print(), abs(), format(),map(), e.t.c. All these built in function comes as libraries of python. Specially Data Science, Machine Learning, Big Data projects or any AI project require much code . Always a bigger code may have repetitions .To avoid this repetition , We use functions in python .I think your mind is completely fill of questions in functions. Get your answers in this article-
Can you Imagine Programming without any function ?
Lets have a practical scenario , Suppose you are a data scientist and you need to develop a code which can fetch data from Stock market for a particular company . You simply wrote the code and achieve the functionality in approximate 200 lines of code without using function .After some time you realize to enhance the code for two other companies . You have to add 400 extra lines of code . Here you will face a special challenge that how will you declare the variables . Choosing different variable name can be difficult for every iteration . In the opposite side , You may use function which will reduce the lines of code and it will encapsulate your variable as well . You must be thinking I can use loop to avoid the repetition but remember loop can not encapsulate your variable . These two are completely different.
Functions Definition : ( Academic Readers)
Functions are the set of instructions. You make functions when it is repeatedly require in the code. Its main purpose is to perform a specific task according to instructions written inside function. There are two main things inside any function.
Parameters in function are also called as input of function. You can have one parameter or more than one or no parameter. In the same way, each function must have to return values. Function can return one or more than one or no values.
Types of Functions in Python
Functions in python are of three types:-
- Pre Defined functions
- User defined functions
- Anonymous functio or Lamda functions
- Pre Defined functions
Pre Defined functions are those functions which are already comes with python standard libraries. For example print(), abs(), help(), max() are some built in functions. Below is the attached overview of built in functions.
User Defined Functions
User defined functions are those functions who are not pre built. You can create as many as user defined function. These type of functions are helpful when you have perform specific task more than once.
Anonymous functions or Lambda functions
If You see the Lambda functions , You will find it has light syntax.You need not to use def keyword with them . Actually It has no identifier type Linkage . I mean you need not to write data type support with these type of functions .
Key Notes about Function Beginner programmers often got confuse between Functions or Methods and Parameters or Arguments. In the next sections you will know the difference between them. Assuming you have knowledge about class. When you create a class, then inside the class you define functions. These functions are know as Methods. You can call and access this function only when instance or object of the class are call. Whereas functions outside any class are standalone. Therefore all methods are functions but all functions are not methods.
Difference between Parameters and Arguments
Beginners always confuse about the difference between parameters and arguments. Even I was thinking parameters and arguments are the same thing. But there is a difference. When you define a function or method , then values inside the bracket are parameters. Arguments are values which are supplied. These values are supplied when you invoke a function.
How to define a functions in python :-
Defining a function is an easy task. You have to just remember the following steps to define a function in python.
Step 1 – There is a reserve keyword to declare the function. Use the key def to declare the function and a function name as a suffix.
Step 2 – Each function should have an parameters. Add parameter name inside the parenthesis. After that add colon to end the line.
Step 3- Add statements to the function to execute.
Step 4 – Each function should have return statement and it is necessary for the function to output something. Without it function will output the error.
What is pass statement in Python –
Usually when you do not want your Python code to perform something but you just need a placeholder . In this case you can use pass statement .
You can see the above code. def used to declare the function. Hello is the name of the function and str is its parameter. print(str) is the statement. At last return is written to indicate that function is over and will return the value. In the above code we have used only one parameter str. But you can use more than one parameters. You can also edit code and modify it to see the changes in the output. The above code is very basic. You can add loops,nested loops to make it more complex. However, when you try to run the above code , you will not see the output . It is because only function is defined. In the next section, you will know how to call a function in python.
How to call a function in python :-
Now, you have understand how to define a function. You will know how to call a function in python in this section. Calling a function requires only one thing, Function must be pre defined. You can execute function by the function name. See the below example.
You can see the above code. We have defined a function and then call the function using the name same as the function name with arguments values. It gives Welcome to Data Science Learner as an output.
What is docstrings and How to add it to Python Function :-
Documentation of every written code is useful for the programmer to read and understand what the functions are doing. In Python we use Docstrings to describes a Function. Doctrings are the descriptions, so that reader can understand what your functions do without reading the whole code.
Docstring are placed after the function declaration. In fact, It is placed between the triple quotation marks “””. The example below has short length of function docstring. But in the real world , its longer. You can find it on a python code of scikit-learn .
You can also write function docstring as “”” in first line, Dsecriptions in the next line and then “”” in the last line like this.
This is function docstings
Types of Function Arguments in Python
Earlier you have learned the difference between parameters and arguments. When any thing is passed as value to the function or method call, then it is argument. While the Parameter are the arguments inside the brackets () when the function is declare.
There are four types of Function arguments in Python in User Defined Functions.
- Default Arguments
- Required Arguments
- Keyword Arguments
- Variable-length Arguments
In Most Scenario , You need to write a function which perform some task even all required argument are not provided by user . In this Scenario we need to define a default value for such argument . Default value is assign using the operator ‘=’ . Look at the following example for more clarification.
You can define more than one parameters in the function. But while calling the function , if you have passed the less number of arguments then you will get an error. Therefore, you must passed the same number of arguments as the parameters in the function definition. These arguments which are passed are known as required arguments. In addition arguments should match the correct position order. If you not provide it in correct positional order there will be syntax error. Below is the example of required arguments.
You can see in the above code, Function have two parameters ‘a‘ and ‘b‘. It print sum of ‘a’ and ‘b’. Therefore ,according to required arguments definition, you have to pass value of ‘a’ and ‘b ‘during the function call. If you call sum(2) with only one parameter then, you will get the following error.
When you write definition of a function you put parameters each with their unique name. These are also call as keyword arguments. When you call the function with arguments with their name, then the function caller automatically identifies arguments by the parameter name.
Keyword arguments has one main advantage over all the other arguments. You don’t have to check are the position orders of parameters are at correct position or not . In fact Python language automatically assign the argument values by reading the name of the arguments. The below example will clarify you in details.
In the above example, when the functions in python Student(name = “John”,age = 24) and Student( age = 27 , name = “Monika”). Python ia ble to identify the keyword arguments position.
Variable – Length Arguments
Generally you were using one, two or three parameters . But what will happen if we want more parameters during the run-time. Sometimes, you require more arguments during the function call. Thus, you have to define variable length arguments for the function. There is one thing that differentiate variable length arguments are that it does not need to be named in the function definition. It is different from required and default arguments. You have to use ‘*‘ asterisk to declare variable-length arguments. The following example will clarify any question about the variable-length argument.
In the above example, there are two parameters arg1 and *varnumber. Line 10 call the function with one parameter and line 11 call it with more than one parameter. Loop may require to print the output of variable length arguments.
You have now known the various types of function arguments. In the next section, you will learn the How to define Anonymous Functions in Python.
How to define Anonymous Functions in Python
Functions that doesn’t have name are called Anonymous Function. Generally Functions have its own name but Anonymous Functions have no name. Other functions are declared using def keyword. Lambda keyword is used to determine Anonymous function. These are the major features of Lambda anonymous function.
- It can take any number of arguments and return only expression.
- It can not be directly call to perform task, as lambda requires an expression
The below is an example of Anonymous Function in python.
You can see in the above example, anonymous function has called with arg1 and arg2 as expression. Function has called after the lambda expression has assigned to multiply. In addition, function has no name but you can call it using sum like multiply(10,20) and multiply(10,10).
You should use anonymous function when require it for shot period of time. It is generally created during the run-time. Anonymous function are mostly useful when you are working with map(), reduce(), filter(), e.t.c.
Scope of Variables in Python
When you declare any variable in the program then you can not access that variable in all locations in a program. Accessing a variable will depend upon where you have declared that variable.
You might be thinking of then what is the scope of variable. You can refer scope as sub part of the program. It means scope is part of the program where variable has declared and you have access to that scope only.
Python language have two types of variables
- Global Variables
- Local Variables
Those variables which are declared outside the function definition are Global Variable. You can access these variables anywhere. It means inside any function, outside, in expression ,e.t.c. In addition, you can use these variable inside more than one function.
Local variables are those various which are declared inside the function. You can access these variables only inside the function. Any output related to local variable will exist only inside the function. Outside the function , output doesn’t relate the local variable.
I think you want more clarification about it. Right!. In fact, The below example , will clear any queries in your mind.
When you run the code you will get the output for inside function. But when you call the Sum function outside function definition , then the sum variable will give the following output.Outside the Function: <built-in function sum>
Tips for better Functions in Python-
Till now we have done with most of the require syntactical knowledge related to functions . In this section we are not going to more discuss that anymore . In that place , This section covers the code refactoring secretes to write readable code . Specially there are so much things which you should keep in the mind while writing functions in Python . Lets understand them one by one-
- Always use lower case in function name . Apart from this , Please choose a description name for you function. Its my personal opinion , You usually beginner concentrate on writing the code which just fulfills the requirement of user . They do not follow the best practices of code generation . They make things working but This creates problem in code maintenance for long run .Suppose you wrote some code today where you do not use descriptive name and just after three years you need to change something over there to enhance the functionality .You have to read the function description( @docstrings if available ) or complete code inside that . On the other hand , If you write the function name appropriately you can understand the overview by its name only . So please remember this tip for the next time when you write the functions in python .
- One function should perform one task at time , Do not overload your function . If you are handling multiple things in single function , You are totally breaking the origin cause of functions in programming .
- You may use underscore in function name if you need to merge more than two words to make it self explanatory .
- Always avoid using global variable inside function . In case you need to use them , try to pass them as argument in you function.
Functions in Python is like heat in human body . You have to know how to define and call the function for better Programming .We have also tried to cover those terms which we use but can not explain properly ,For example : The difference between Parameters and Arguments . There are many keywords reserved functions in the python. which You have to just call only when require. This actually make programming too easy . In addition, you can also make User Defined Functions( UDF) ,if there is need of customization functions in your code. Python is the fasted growing language. Its community is very large and you will see its huge demand in the field of Data Science, Machine Learning, and Big Data.
Apart from this article , below are the relevant articles to know basics of Python and its applications in other fields.
- Introduction to Python .
- Python overview Guide for beginner .
- How to install python
- Why is Python best Machine Learning Language .
- Introduction to Machine Learning
- Top Machine Learning Libraries in Python.
I hope You have got the answer for your question “ Functions in Python ” . If you think there is some thing that we should include in this article . To make this article more informative and complete with your own thoughts and suggestion Please comment below .
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.