Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python Function1

The document provides an overview of Python functions, including their definition, types, and how to create and use them. It covers built-in functions, user-defined functions, arguments vs parameters, and the use of modules and import statements. Additionally, it explains the return statement and various types of function arguments such as required, keyword, default, and variable-length arguments.

Uploaded by

julian.ams041
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Function1

The document provides an overview of Python functions, including their definition, types, and how to create and use them. It covers built-in functions, user-defined functions, arguments vs parameters, and the use of modules and import statements. Additionally, it explains the return statement and various types of function arguments such as required, keyword, default, and variable-length arguments.

Uploaded by

julian.ams041
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Python Function

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:

They are not pre-defined functions. The user


creates their own function to fulfill their specific
needs.
Syntax
to create USER DEFINED FUNCTION
def function_name([comma separated list of
parameters]):
statements….
statements….
Important points to remember:

• Keyword def that marks the start of the function header.


• A function name to uniquely identify the function. Function naming follows
the same rules of writing identifiers in Python.
• Parameters (arguments) through which we pass values to a function. They are
optional.
• A colon (:) to mark the end of the function header.
• Optional documentation string (docstring) to describe what the function does.
• One or more valid python statements that make up the function body.
Statements must have the same indentation level (usually 4 spaces).
• An optional return statement to return a value from the function.

Function header: The Header of a function specifies the name of the


function and the name of each of its parameters. It begins with the
keyword def.
Parameters: Variables that are listed within the parenthesis of a
function header.
Function Body: The block of statements to be carried out, ie the action
performed by the function.
Indentation: The blank space needed for the python statements. (four
spaces convention)
Arguments Vs Parameters:

Arguments The values being passed through a


function call statement are called argument (or
actual parameter or actual argument).
Parameters: The values received in the
function definition/header are called parameter
(or formal parameter of formal argument)
The number of arguments and parameters should
def sip(p,r,t):
always be equal except for the variable length list.
p=(p*r*t)/100
Arguments in Python can be one of these values
types: The following are some valid function call statements:
1) literals 2) variables 3) expressions sip(10000,3,4) #these are literal arguments
p=10000
sip(p,3,4) # one variable and two literal arguments
sip(p,r*2,4) # one variable, one expression and one
literal argument
USER DEFINED FUNCTIONS EXAMPLE

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)

n=int(input("Enter a number :")) n=int(input("Enter a number :"))


s=Show(n) s=Show(n)
print(s) print(s)
Output:
Output: Enter a number :10
Enter a number :5 1
1 2
2 3
3 4
4 5
None 6
Function Arguments:

A function by using the following types of formal arguments:


– Required arguments
– Keyword arguments
– Default arguments
– Variable-length arguments
Required arguments/Positional arguments:

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 program to illustrate the use of keyword arguments


def Surface_Ar(l,b,h):
print("Length: ",l)
print("Breadth: ",b)
print("Height: ",h)
Output:
ar=2*(l*b+b*h+l*h)
Length: 20
print("Surface Area :",ar)
Breadth: 12
#Main Program
Height: 10
Surface_Ar(b=12, h=10,l=20)
Surface Area : 1120
Default arguments:

 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.

Example1: Example2: Example3:


def showInfo(name,std,roll=14): def showInfo(name,std='XII-A',roll=14): def showInfo(name,std='XII-A',roll=14):
#Here, roll is assigned with default value. # Here, std and roll are assigned with default values
print("Roll No.:",roll)
print("Roll No.:",roll) print("Roll No.:",roll)
print("Name :", name) print("Name :", name) print("Name :", name)
print("Class :",std) print("Class :",std) print("Class :",std)

#main program #main program #main program


showInfo('Aviral',’XII’) # missing third argument showInfo('Aviral') # Here, two arguments missing showInfo('Aviral','XII-B',24)

Output: Output: Output:


Roll No.: 14 Roll No.: 14 Roll No.: 24
Name : Aviral Name : Aviral Name : Aviral
Class : XII Class : XII-A Class : XII-B
Variable-length arguments:
 Some times making the program we are not sure about the number of arguments, so python defines the variable
length arguments. With (*) asterisk symbol we can use this concept.
Example1:
Example2: Example3: arguments passed as a tuple
# beginning of the method
def sum(*args): def multiplier(*num): def display(*names):
finalResult = 0 prod = 1 for name in names:
#beginning of for loop #initialize prod variable with zero print("Welcome ", name)
for arg in args: for i in num: print("Welcome again ", names[3])
finalResult = finalResult + arg prod = prod * i
#Main Program
return finalResult print("Product:",prod) display("Raj","Rajan", "Aviral",
#main program "Yashu","Simmi")
#main program printing the values
print(sum(10, 20)) # 30 multiplier(3,5)
multiplier(1,2,4) Output:
print(sum(10, 20, 30)) # 60 Welcome Raj
print(sum(10, 20, 2)) # 32 multiplier(2,2,6,7) Welcome Rajan
Output: Welcome Aviral
Output:
30 Product: 15 Welcome Yashu
Product: 8 Welcome Simmi
60
Product: 168 Welcome again Yashu
Example:
Syntax Error non-default argument

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

You might also like