Advantages of Using Function
- Ease of Use: This allows ease in debugging the code and prone to less error.
- Reusability: It allows the user to reuse the functionality with a different interface without typing the whole program again.
- Ease of Maintenance: It helps in less collision at the time of working on modules, helping a team to work with proper collaboration while working on a large application.
What is Function?
A function can be defined as the organized block of reusable code which can be called whenever required. A function is a block of code which only runs when it is called. Basically two types of function.
1-SDF-System Defined Function
2-UDF-User Defined Function.
- Python allows us to divide a large program into the basic building blocks known as function.
- A function can be called multiple times to provide reusability and modularity to the python program.
- The idea is to put some commonly or repeatedly done task together and make a function.
Function can be categorized in to:
- Non-Parameterized Function
- Parameterized Function
Function Definition
In python, we can use def keyword to define the function.
Syntax:
def function_name(parameter_list):
function-definition
return <expression>
- The function block is started with the colon (:)
- All the same level block statements remain at the same indentation.
- A function can accept any number of parameters that must be the same in the definition and function calling.
Function Calling
In python, a function must be defined before the function calling otherwise the python interpreter gives an error.
Once the function is defined, we can call it from another function or the python prompt.
To call the function, use the function name followed by the parentheses.
def hello_world():
#function declaration
print(“This is first statement”)
#function definition
print(“This is second statement”)
hello_world()
Non-Parameterized Function
The non-parameterized function does not require any variable name in their declaration and calling.
Example:
def area_circle():
r=float(input(“Enter Radius of Circle:”))
a=3.14*r*r
print(“Area of circle:”,a)
area_circle() #function calling
Parameterized Function
The parameterized function require variable name in their declaration and calling.
Function parameters
The information into the functions can be passed as the parameters. The parameters are specified in the parentheses.
A function may have any number of parameters.
Multiple parameters are separated with a comma
Example 1:
def area_circle(r):
a=3.14*r*r
print(“Area of circle:”,a)
radius=float(input(“Enter Radius:”))
area_circle(radius)
- Here, the function named area_circle() is declared with empty().
- This means, the function called with empty() i.e. calling does not requires any parameter.
Example 2: Python function to calculate area of rectangle using parameterized function
def area_rect(l,b): #parameterized function
area_lb=l*b
print(“Area of Rectangle:”,area_lb)
len=float(input(“Enter Length of rectangle:”))
brth=float(input(“Enter Breadth of rectangle:”))
area_rect(len, brth)
Output:
Enter Length of rectangle:30
Enter Breadth of rectangle:20
Area of Rectangle: 600.0
Return Statement
A function may return a value using return keyword. When a function produces a result, there are two possibilities:
a) The value of output is preserved within the function. As in above example.
b) Transfer the value of output to calling function.
i) Return statement is used in this scenario.
ii) A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller.
c. The statements after the return statements are not executed.
d. If the return statement is without any expression, then the special value None is returned.
Example 1:
def si_int(p,r,t):
si=(p*r*t)/100
return si #returning the value of si to the calling function
s=si_int(20000,8.5,3)
print(“Simple Interest=”,s)
- In above example, the function si_int() will calculate the simple interest in variable named si and returns the value of si to the function calling.
- At function calling, the returned value is stored in variable named s.
- Now, we can use the value of s as per requirement. In above example, the value of s gets printed using print statement.
Example 2:
def area_rect(l,b): #parameterized function
area_lb=l*b
return area_lb #returning the value of area_lb to calling function
len=float(input(“Enter Length of rectangle:”))
brth=float(input(“Enter Breadth of rectangle:”))
# Ar will store the value of area_lb, which is returned by the function
Ar=area_rect(len, brth)
Output:
Enter Length of rectangle:20
Enter Breadth of rectangle:10
Area of Rectangle: 200.0
Types of Parameter
There may be several types of arguments which can be passed at the time of function calling.
- Required arguments
- Keyword arguments
- Default arguments
- Variable-length arguments
Required Arguments
The required arguments are required to be passed at the time of function calling with the exact match of their positions in the function call and function definition. If either of the arguments is not provided in the function call, or the position of the arguments is changed, then the python interpreter will show the error.
Example 1:
def calculate(a,b):
return a+b
sum1=calculate(10) # this causes an error as we are missing a required arguments b.
print(“Sum=“,sum)
Output: calculate() missing 1 required positional argument: ‘b’
Example 2:
def calculate(a,b):
return a+b
sum1=calculate(10,10)
print(“Sum=“,sum)
Output: Sum=20
Keyword Arguments
Python allows us to call the function with the keyword arguments. This kind of function call will enable us to pass the arguments in the random order.
Example1:
#The function simple_interest(p, t, r) is called with the keyword arguments the order of arguments doesn’t matter in this case
def simple_interest(p,t,r):
return (p*t*r)/100
print(“Simple Interest: “,simple_interest(t=10,r=10,p=1900))
Output: Simple Interest: 1900.0
Note: In this case the name of argument is same in calling and definition.
Example 2:
#The function simple_interest(p, t, r) is called with the keyword arguments the order of arguments doesn’t matter in this case
def simple_interest(p,t,r):
return (p*t*r)/100
x=float(input(“Enter Amount”))
y=float(input(“Enter Time”))
z=float(input(“Enter Rate”))
print(“Simple Interest: “,simple_interest(t=y,r=z,p=x))
Output:
Enter Amount12000
Enter Time5
Enter Rate5
Simple Interest: 3000.0
- If we provide the different name of arguments at the time of function call, an error will be thrown.
simple_interest(20000,rate=7.5, time=6) #error
- The python allows us to provide the mix of the required arguments and keyword arguments at the time of function call. simple_interest(20000,t=5,r=6.5)
- The required argument must not be given after the keyword argument.
simple_interest(20000,r=7.5,6) #error
Default Arguments
Python allows us to initialize the arguments at the function definition. If the value of any of the argument is not provided at the time of function call, then the default value for the argument will be used.
Example 1:
def printme(name,age=22):
print(“Name:”,name,”\nAge:”,age)
printme(“Ravi”) # name=Ravi age=22 (default value)
printme(“Sachin”, 33) #name =Sachin age=33
Output:
Name: Ravi
Age: 22
Name: Sachin
Age: 33
Variable Length Arguments
Variable length argument is a feature that allows a function to receive any number of arguments. However, at the function definition, we have to define the variable with * (star) as *<variable – name >.
Example 1:
def printme(*names):
print(“type of passed argument is “,type(names))
print(“printing the passed arguments…”)
for name in names:
print(name)
#calling printme function
printme(“Rahul”,”Prashant”,”sunita”,”Sandeep”)
Output:
type of passed argument is <class ‘tuple’>
printing the passed arguments…
Rahul
Prashant
sunita
Sandeep
Example 2:
def adder(*num):
sum = 0
for n in num:
sum = sum + n
print(“Sum:”,sum)
adder(3,5) #calling adder with 2 argument
adder(4,5,6,7) #calling adder with 4 argument
adder(1,2,3,5,6) #calling adder with 5 argument
Output:
Sum: 8
Sum: 22
Sum: 17
Local Variable
- A local variable is a type of variable declared within programming block or function.
- It can only be used only inside that function or code block in which they were declared.
- The local variable exists until the block of the function is in under execution. After that, it will be destroyed automatically.
Example 1:
def func():
a=10
print(“Value of a in function:”,a)
func()
print(“Value of ‘a’ outside function:”,a)
Output: name ‘a’ is not defined
In example1, it is clearly shown that the value of variable ‘a’ is only accessible inside the function func(). The value variable ‘a’ cannot be accessible outside the function because variable ‘a’ is a local variable of the function func(). It can only be accessible inside the function func().
Global Variable
- Global variables are defined outside of a subroutine or function.
- The global variable will hold its value throughout the lifetime of a program.
- They can be accessed within any function defined for the program.
Example 1:
a=10
def func():
print(“Value of a in function:”,a)
func()
print(“Value of ‘a’ outside function:”,a)
Output:
Value of a in function: 10
Value of ‘a’ outside function: 10
Here, variable ‘a’ is defined outside the function func(). The variable ‘a’ will now become a global variable. It can be accessed inside any function as well as outside the function.
Global Keyword
So far, we haven’t had any kind of a problem with global scope. So let’s take an .
Example 1:
i=10 #global variable
def counter():
i=20 #local variable of function counter
print(“Value of i in function:”,i)
counter()
print(“Value of i Outside Function:”,i)
Output:
Value of i in function: 20
Value of i Outside Function: 10
Now, when we make a reference to ‘i’ outside this function, we get 10 instead of 20.
Global keyword is a keyword that allows a user to modify a variable outside of the current scope.
- It is used to create global variables from a non-global scope i.e. inside a function.
- Global keyword is used inside a function only when we want to do assignments or when we want to change a variable.
- Global is not needed for printing and accessing.
Rules of Global Keywords
If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
- Variables that are only referenced inside a function are implicitly global.
- We Use global keyword to use a global variable inside a function.
- There is no need to use global keyword outside a function.
Use of Global Keywords
To access a global variable inside a function there is no need to use global keyword.
Example 1:
# global variable
a = 15
b = 10
# function to perform addition
def add():
c = a + b
print(c)
# calling a function
add()
Output: 25
If we need to assign a new value to a global variable then we can do that by declaring the variable as global.
Code: Without global keyword
a = 15
# function to change a global value
def change():
# increment value of a by 5
a = a + 5
print(a)
change()
If we need to assign a new value to a global variable then we can do that by declaring the variable as global.
Code : Without global keyword
a = 15
# function to change a global value
def change():
a = a + 5 # increment value of a by 5
print(a)
change()
Output: UnboundLocalError: local variable ‘a’ referenced before assignment
This output is an error because we are trying to assign a value to a variable in an outer scope. This can be done with the use of global variable.
Code : With global keyword
# Python program to modify a global
# value inside a function
x = 15
def change():
global x # using a global keyword
x = x + 5 # increment value of a by 5
print(“Value of x inside a function :”, x)
change()
print(“Value of x outside a function :”, x)
Output:
Value of x inside a function : 20
Value of x outside a function : 20
Python docstrings
Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods.
General Rules:
- The doc string line should begin with a capital letter and end with a period.
- The first line should be a short description.
- If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.
- The following lines should be one or more paragraphs describing the object’s calling conventions, its side effects, etc.
Declaring Docstrings: The docstrings are declared using “””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring.
Accessing Docstrings: The docstrings can be accessed
- using the __doc__ method of the object or
- using the help function.
Example:
def my_function():
“””Demonstrate docstrings and does nothing really.”””
return None
print(“Printing DocString Using __doc__:”)
print(my_function.__doc__ )
print(“Printing DocString Using help function:”)
help(my_function)
Output:
Printing DocString Using __doc__:
Demonstrate docstrings and does nothing really.
Printing DocString Using help function:
Help on function my_function in module __main__:
my_function()
Demonstrate docstrings and does nothing really.