Python Functions Examples
A Function in Python is used to utilize the code in more than one place in a program. It is also called method or procedures. Python provides you many inbuilt functions like print(), but it also gives freedom to create your own functions.
How to define and call a function in Python
Function in Python is defined by the “def ” statement followed by the function name and parentheses ( () )
Let us define a function by using the command ” def func1():” and call the function. The output of the function will be “I am learning Python function”.
The function print func1() calls our def func1(): and print the command ” I am learning Python function None.”
There are set of rules in Python to define a function.
- Any args or information parameters ought to be put within these parentheses
- The capacity first explanation can be a discretionary articulation docstring or the documentation string of the capacity
- The code within every capacity starts with a colon (:) and ought to be indented (space)
- The announcement return (expression) exits a capacity, alternatively going back an incentive to the caller. A return proclamation with no args is equivalent to return None.
Significance of Indentation (Space) in Python
Before we get familiarize with Python capacities, it is important that we understand the space rule to declare Python capacities and these rules are material to other components of Python also like declaring conditions, loops or variable.
Python follows a particular style of space to characterize the code, since Python capacities don’t have any explicit start or end like curly braces to demonstrate the start and stop for the capacity, they need to rely on this space. Here we take a straightforward model with “print” order. At the point when we write “print” work right underneath the def func 1 (): It will show a “space error: anticipated an indented block”.
Now, when you add the indent (space) in front of “print” function, it should print as expected.
At least, one indent is enough to make your code work successfully. But as a best practice it is advisable to leave about 3-4 indent to call your function.
It is likewise necessary that while declaring space, you need to keep up a similar indent for the rest of your code. For instance, in underneath screen shot when we call another announcement “still in func1” and when it isn’t declared right beneath the first print explanation it will show a space error “unindent doesn’t coordinate some other space level.”
Now, when we apply same indentation for both the statements and align them in the same line, it gives the expected output.
Return order in Python indicates what incentive to offer back to the caller of the capacity.
How about we understand this with the accompanying model
Stage 1) Here – we see when capacity isn’t “return”. For instance, we need the square of 4, and it should offer response “16” when the code is executed. Which it gives when we essentially use “print x*x” code, yet when you call work “print square” it gives “None” as a yield. This is on the grounds that when you call the capacity, recursion doesn’t occur and tumble off the finish of the capacity. Python returns “None” for coming up short off the finish of the capacity.
Step 2) To make this clearer we replace the print command with assignment command. Let’s check the output.
When you run the command “print square (4)” it actually returns the value of the object since we don’t have any specific function to run over here it returns “None”.
Step 3) Now, here we will see how to retrieve the output using “return” command. When you use the “return” function and execute the code, it will give the output “16.”
Stage 4) Functions in Python are themselves an item, and an article has some worth. We will here perceive how Python treats an article. At the point when you run the order “print square” it returns the estimation of the item. Since we have not passed any argument, we don’t have a particular capacity to run over here it returns a default esteem (0x021B2D30) which is the area of the article. In practical Python program, you probably won’t ever need to do this.
Arguments in Functions
The argument is a value that is passed to the function when it’s called.
In other words on the calling side, it is an argument and on the function side it is a parameter.
Let see how Python Args works –
Step 1) Arguments are declared in the function definition. While calling the function, you can pass the values for that args as shown below
Step 2) To declare a default value of an argument, assign it a value at function definition.
Example: x has no default values. Default values of y=0. When we supply only one argument while calling multiply function, Python assigns the supplied value to x while keeping the value of y=0. Hence the multiply of x*y=0
Step 3) This time we will change the value to y=2 instead of the default value y=0, and it will return the output as (4×2)=8.
Step 4) You can also change the order in which the arguments can be passed in Python. Here we have reversed the order of the value x and y to x=4 and y=2.
Step 5) Multiple Arguments can also be passed as an array. Here in the example we call the multiple args (1,2,3,4,5) by calling the (*args) function.
Example: We declared multiple args as number (1,2,3,4,5) when we call the (*args) function; it prints out the output as (1,2,3,4,5)
- In Python 2.7. work overloading isn’t supported in Python. Capacity Overloading is the ability to create various techniques for a similar name with a different execution. Capacity Overloading is completely supported in Python 3
- There is quite a disarray among strategies and capacities. Techniques in Python are related with object occurrences while work are definitely not. At the point when Python calls a strategy, it binds the first parameter of that call to the appropriate article reference. In straightforward words, an independent capacity in Python is a “work”, whereas a capacity that is an attribute of a class or a case is a “strategy”.
Here is the complete Python 3 code
#define a function def func1(): print ("I am learning Python function") print ("still in func1") func1() def square(x): return x*x print(square(4)) def multiply(x,y=0): print("value of x=",x) print("value of y=",y) return x*y print(multiply(y=2,x=4))
Here is the complete Python 2 code
#define a function def func1(): print " I am learning Python function" print " still in func1" func1() def square(x): return x*x print square(4) def multiply(x,y=0): print"value of x=",x print"value of y=",y return x*y print multiply(y=2,x=4)
Capacity in Python is a bit of reusable code that is utilized to perform single, related activity. In this article, we will see
- Capacity characterized by the def explanation
- The code block within every capacity starts with a colon (:) and ought to be indented (space)
- Any arguments or information parameters ought to be put within these parentheses, and so forth.
- At any rate one indent ought to be left before the code after declaring capacity
- Same indent style ought to be kept up throughout the code within def work
- For best practices three or four indents are considered best before the announcement
- You can utilize the “return” order to return values to the capacity call.
- Python will print a random worth like (0x021B2D30) when the argument isn’t provided to the calling capacity. Model “print work.”
- On the calling side, it is an argument and on the capacity side it is a parameter
- Default an incentive in argument – When we gracefully just a single argument while calling duplicate capacity or some other capacity, Python doles out the other argument naturally
- Python empowers you to reverse the order of the argument too