In this article, we will tell about Python functions. We should also know about function defining function calling and variable arguments. Let’s have a quick look on the below contents :
- Introduction
- Function Creation
- Definition
- Declaration
- Call
- Arguments
- Required arguments
- Keyword argument
- Default argument
- Variable-length argument
- Arbitrary Keyword
- List in arguments
- Return value
- Pass Statement
- Recursion in Python
Introduction
A function is a block of organized and reusable program code that performs a single, specific, and well-defined task. Python enables the breakage of a program into functions. The code of one function is completely insulated from the codes of the other functions.
Function Creation
A function is created using the def keyword.
def func():
print("Creation of function done!")
Function Definition
A function definition consists of a function header that identifies the function, followed by the body of the function containing the executable code for that function.
Function Declaration
A function declaration is a declaration statement that identifies a function with its name, a list of arguments that it accepts, and the type of data it returns.
Function Call
When a function is invoked, the program control jumps to execute the statements that are a part of that function. once the called function is executed the program control passes back to the calling function. The call is made using the parenthesis. To know more you can refer to this site.
def func():
print("Creation of function done!")
func()
Arguments
there are 4 types of arguments in Python. Those are:
- Required arguments
- Keyword arguments
- Default arguments
- Variable-length arguments
Required arguments
In this type of arguments, the arguments passed to a function in correct positional order. Also, the number of arguments in the function call should exactly match with the number of arguments specified in the function definition.
def display(str):
print(str)
str ="Hello"
display(str) #returns Hello
The function displays the string only when number and type of arguments in the function call matches with the specified in the function definition, otherwise a TypeError is returned.
def display():
print("Hello")
display("Hi") #returns TypeError : display() takes no arguments(1 given)
def display(str):
print(str)
display(str) #returns TypeError : display() takes exactly 1 argument(0 given)
Keyword argument
This arguments help the function to identify the arguments by the parameter name. Having a required argument after keyword arguments will cause error. Its order is not important. In no case, the argument should receive a value more than once.
def display(str, int, float):
print("The string is : ",str)
print("The integer value is : ",int)
print("The float value is : ",float)
display(float=10.56,str="Hello",int=12)
Default Arguments
If a value is not provided in the function call, a default argument assumes a default value. Users can specify a default value for one or more arguments. It uses the assignment operator ” + “.
def display(name, course = "Btech"):
print("Name:" +name)
print("Course:",course)
display(course ="BBA",name = "Shreya") #Keyword Arguments
display(name = "Meghna") #Default arguments
Variable-Length Arguments
Python allows programmers to make function calls with the arbitrary number of arguments. The function definition uses an asterisk ( * ) before the parameter name. To know more you can refer to this site.
Syntax : def function([arg1, arg2 ,……] *var_args_tuple ): function statements return [expression]
def func(name, *fav_subjects):
print(name, " likes to read ")
for subjects in fav_subjects:
print(subject)
func("Itika", "Mathematics", "digital")
func("Saurav", "C", "Design and Analysis of Algorithm", "Python")
func("Saurav")
Arbitrary Keyword Arguments, **kwargs
When the number of arguments is not known to us we use a double asterisk (**) before the parameter name in the function definition. In this way function receive lots of arguments and access it.
def my_fun(**girl):
print("Her mothertongue is " + girl["mtongue"])
my_fun(fname = "Tiyasa", mtongue = "bengali") #returns Her mothertongue is bengali
Passing a List as an Argument
If we send a list as an argument through the function it will become a list after passed through the function.
def fun(clothes):
for i in clothes:
print(i)
bottom_wear=["jeans", "leggings", "plazo"]
fun(bottom_wear)
Return Values
When a function return some values we use the return statement.
def fun(a):
if(a%2==0):
return 1
else:
return -1
a=12
flag=fun(a)
if(flag==1):
print("The number is even")
if(flag==-1)
print("The number is odd") #returns The number is even
The pass Statement
We all know that function definition shouldn’t be empty. But for some reason the function definition is empty we can simply use the pass statement to avoid error.
def func():
pass
Recursion
Recursion is more of a top-down approach to problem-solving in which the original problem is divided into smaller sub-problems. This is an excellent way of solving complex problems and it can be defined in recursive terms.
Pros:
- Recursive solutions often tend to be shorter and simpler than non-recursive ones.
- Code is clearer and easier to use.
- It uses the original formula to solve a problem
- It follows a divide and conquer strategy.
Cons:
- It is implemented using system stack. If the stack space on the system is limited, recursion to deeper level will be difficult.
- It is difficult to find bugs, particularly when using global variables.
- It takes a huge amount of memory.
So, the following is a recursive function call code to print the Fibonacci series recursion.
def fibonacci(n):
if(n<2):
return 1
return (fibonacci(n-1)+fibonacci(n-2))
n=5
for i in range(n):
print("Fibonacci(" ,i, ") = ",fibonacci(i))