Python Function1
Python Function1
Narain Ji Srivastava
WORKING WITH FUNCTIONS
Important Topics
Function Definition
Types of Function
Creating Python Module
The import Statement
The ‘from’ import statement
User Defined Function
Arguments Vs Parameters
Features of return Statement
Function Definition:
A function is a subprogram that acts on data and often returns a value.
Advantages of Functions
• Reducing duplication of code
• Decomposing complex problems into simpler pieces
• Improving clarity of the code
• Reuse of code
• Information hiding
a) Built in functions: Built-in functions are the pre-defined function in Python that can
be directly used.
Example: input(), print(), bin(), oct() etc.
b) Function in a Module: A module is simply a Python file with a .py extension that can
be imported inside another Python program.
OR
A module is but a piece of Python code. A module allows you to logically organize your
Python code. A module is a file that contains Python statements and definitions. The
modules in Python have the .py extension.
Creating a Python Module
A module handles small program parts or specific utility or function. A module can define functions,
classes and variables. A module can also include runnable code.
In Python, the modules or user-defined functions are created with the def keyword.
Syntax:
def modue_name/function_name():
Python_program_statements
Example: display message “Welcome to Python……”. So let‟s created module file “Test.py”
Test.py
def displayMsg(name):
print("Welcome to Python "+name)
Save and Run Module (F5). Now call „displayMsg‟
>>> displayMsg("Module") #calling displayMsg
Welcome to Python Module
Loading the module in our python code : We need to load the module in our python code
to use its functionality. Python provides two types of statements as defined below.
1.The import statement 2. The from-import statement
The import statement
Example:
Save file Test.py
def Add_TumNum():
x=int(input("Enter first no. :"))
y=int(input("Enter second no. :"))
r=x+y
print("Sum :",r)
Save and Run Module (F5).
For example:
Importing Module as Alternate Name: >>> import Test as T
you can also import as entire module an >>> T.Add_TumNum()
alternate name. The syntax is: Enter first no. :36
import <module_name> as <alt_name> Enter second no. :64
Sum : 100
Importing Module in another Program
Arguments
In the user-defined function topic, we learned about defining a function and calling it. Otherwise, the
function call will result in an error. Here is an example.
Test.py
def Add_TwoNum(x,y): # x and y two arguments/parameters
r=x+y
return r
def Diff_TwoNum(x,y):
r=x-y
return r
def Mul_TwoNum(x,y):
r=x*y
return r
def Div_TwoNum(x,y):
if(y==0):
print("Division error...")
elif(x>y):
r=x/y
return r
import Test as t
x=int(input("Enter first no. :"))
Create New file Calculate,py and y=int(input("Enter second no. :"))
print("Addtion \t:",t.Add_TwoNum(x,y))
save same folder print("Substract\t:",t.Diff_TwoNum(x,y))
print("Multiplication\t:",t.Mul_TwoNum(x,y))
print("Dividation\t:",t.Div_TwoNum(x,y))
The ‘from’ import statement
The from statement allows the user to import only some specific functions of a module in a
Python code. The syntax of using from import statement is as shown below:
Example: The from import * statement
from math import sqrt, factorial # importing math module.
print("Square root of 16 :", sqrt(16)) # show the square root of We can also make all the functions of a
16 module accessible in a program by
print("Factorial of 5 :", factorial(5)) # show the factorial of 5 using from import * statement.
Note: with reference to the above example, the functions (sqrt Example
and factorial) are specifically mentioned when math module from math import *
imported. They are not allowed include the module name
print(sqrt(25)) # output: 5
(math) while using the functions in the class.
Output:
Square root of 16 : 4.0
Factorial of 5 : 120
User Defined function:
Example : Write a Python function sip(p,r,t) where p as principal, r as rate and t and time.
def sip(p,r,t): #Here p, r and t
are parameters Output:
s=(p*r*t)/100 Enter principal :10000
return s Enter rate :8
Enter time :5
#Main Program
p=int(input("Enter principal :"))
Simple interest : 4000.0
r=float(input("Enter rate :"))
t=int(input("Enter time :"))
print("Simple interest :", sip(p,r,t))
# Here p, r and t are arguments
RETURNING VALUES FROM FUNCTION
(Using return keyword)
Functions in Python may or may not return a value. Example:
There are two types of functions in Python: def sip(p,r,t): #Here p, r and t are parameters
1) Functions returning some value called non- s=(p*r*t)/100
void functions (using return keyword) return s # Return outcomes to the caller program.
2) Functions not returning any value
# Main Program
called void functions p=int(input("Enter principal :"))
r=float(input("Enter rate :"))
Return statement: The return statement t=int(input("Enter time :"))
passes the control back to the caller program print("Simple interest :", sip(p,r,t))
(main program). It is the last statement of the # Here p, r and t are arguments
function body which can also referred to
as Function Terminator.
Syntax : return <value>
Features of Return Statement:
1) It is the last statement of the function body, where the Example :
function gets terminated. def calculate(m,n):
2) No statement in the function will be executed after the add=0
return statement. add=m+n
3) A non-returnable function may or may not use return return add # here terminate the function
statement. p=m+n # it is not executed
Non-returnable function with a return statement but doesn’t pass
Non-returnable function without return statement
any value to the caller
def perimeter(l, w):
def perimeter(l, w):
result = 2 * (l + w)
result = 2 * (l + w)
print("Perimeter of a Rectangle " = ", perimeter) #value doesn’t
return result # value return
return
return #Main Program
#Main Program l = float(input('Please Enter the L of a Triangle: '))
l = float(input('Please Enter the L of a Triangle: ')) w = float(input('Please Enter the W of a Triangle: '))
w = float(input('Please Enter the W of a Triangle: ')) print("Perimeter of a Rectangle = ", perimeter(l,w))
print("Perimeter of a Rectangle using", l, "and", w, " = ", perimeter)
Features of Return Statement:
4) A Python function may be return multiple values to its called program(main program).
Example2: Example3
Example1: def operation(n1,n2):
def getPerson():
def multiple(): add=n1+n2
name = "Narain Ji" sub=n1-n2
operation = "Sum:" age = 45 mul=n1*n2
total = 5+10 country = "India" div=n1/n2
return name,age,country return add,sub,mul,div
return operation, total;
name,age,country = getPerson() #main program
n1,n2=55,5
operation, total = multiple() print(name)
r1,r2,r3,r4=operation(n1,n2)
print(operation, total) print(age) print(n1,'+',n2,'=',r1)
print(country) print(n1,'-',n2,'=',r2)
---------------------------------- ---------------------------------- print(n1,'*',n2,'=',r3)
#Output #Output: print(n1,'/',n2,'=',r4)
Sum: 15 Narain Ji --------------------------------
45 #Output
India 55 + 5 = 60
55 - 5 = 50
55 * 5 = 275
55 / 5 = 11.0
Features of Return Statement:
5) Remember: multiple return values can be returned with the help of a single return
statement cannot use multiple return statements.
Example:
Modified Code:
def operation(n1,n2):
add=n1+n2 def operation(n1,n2):
sub=n1-n2 add=n1+n2
return add sub=n1-n2
return sub return add, sub #or return (add, sub)
# above code use two return statements,
#so it will result in an error. #Main Program
#Main Program n1,n2=55,5
n1,n2=55,5 r1,r2=operation(n1,n2)
r1,r2=operation(n1,n2) print(n1,'+',n2,'=',r1)
print(n1,'+',n2,'=',r1) print(n1,'-',n2,'=',r2)
print(n1,'-',n2,'=',r2)
Features of Return Statement:
6) A function may have more than one termination points. But, only one
return statement will pass the control back to the caller program.
Example:
def largest(n1,n2):
if n1>n2:
return n1
else:
return n2
#Main Program
n1,n2=5,25
print("Largest value :",largest(n1,n2))
Output: Largest value: 25
Features of Return Statement:
7) Once the control exits from a function, it cannot get back into the function block for any
further execution. Example:
def Show(p): def Show(p):
a=p a=p
for i in range(1,p): for i in range(1,p):
if (i>5): if (i>5):
return i return i
print(i) print(i)
Required arguments are the arguments passed to a function in correct positional order.
def simpleIntrest(p,r,t): #Here p, r and t are parameters
s=(p*r*t)/100
return s
# Main Program
p=int(input("Enter principal :"))
r=float(input("Enter rate :"))
t=int(input("Enter time :"))
print("Simple interest :", simpleIntrest (p,r,t))
# Here p, r and t are arguments
Keyword arguments:
The arguments used with the same variable names of the parameters are known as keyword arguments.
Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the
caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the
keywords provided to match the values with parameters.
Keep in Mind
· The passed keyword name should match with the actual keyword name with parameters.
· There should be only one value for one parameter.
A default argument is an argument that assumes a default value if a value is not provided in the function call for that
argument.
One or more parameters are directly assigned with the default values (=) sign.
In case, you pass an argument corresponding to a parameter that is already assigned a default value, it will
be overwritten with the given argument.
The corresponding argument should always be placed right to left. Default arguments must be provided from right to left.
In above code, the parameters with default arguments are place prior to the parameter without default argument.
Hence, they will result in error when executed.
THANK YOU
Visit my blog :https://csnip2020.blogspot.com/
Click Like and Follow button