Python Tutorial: Python Functions

Sunday, 16 August 2020

Python Functions

Functions:

A function is a block of a code (or statement) that performs a specific task and runs only when it is called.

A function block begins with the keyword def followed by the function name and parameter ()

Advantages of functions:

  • Program development made easy and fast
  • Program testing becomes easy
  • Code sharing becomes possible
  • Code re-usability increases
  • Increases program readability

(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).

Importing Module as Alternate Name: you can also import as entire module an alternate name. The syntax is:

import <module_name> as <alt_name>

For example:

>>> import Test as T

>>> T.Add_TumNum()

Enter first no. :36

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. :"))

y=int(input("Enter second no. :"))

print("Addtion \t:",t.Add_TwoNum(x,y))

print("Substract\t:",t.Diff_TwoNum(x,y))

print("Multiplication\t:",t.Mul_TwoNum(x,y))

print("Dividation\t:",t.Div_TwoNum(x,y))

Output

Example: Find Factors of given number

def print_factors(x):

   print("The factors of",x,"are:")

   for i in range(1, x + 1):

       if x % i == 0:

           print(i,end=",")

 

num = 64    # you can change number

print_factors(num)

 

Example:

import math          # importing math module.

a=math.sqrt(9)

b=math.factorial(5)

print(“a=”,a)       # show the square root of 9

print(“b=”, b)           # show the factorial of 5

Output:

==================== RESTART: E:/Python/module.py ====================

a= 3.0

b= 120

 

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:

from math import sqrt, factorial      # importing math module.

print("Square root of 16 :", sqrt(16)) # show the square root of 16

print("Factorial of 5 :", factorial(5)) # show the factorial of 5

Note: with reference to the above example, the functions (sqrt and factorial) are specifically mentioned when math module imported. They are not allowed include the module name (math) while using the functions in the class.

Output:

====================== RESTART: E:/Python/module.py ======================

Square root of 16 : 4.0

Factorial of 5 : 120

 

The from import * statement

We can also make all the functions of a module accessible in a program by using from import * statement.

Example

from math import *

print(sqrt(25))                 # output: 5

(a)  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….

Save the above source code in python file and execute it

Important points to remember:

 

1)  The first line of the function called function header must begin with the Keyword ‘def’ followed by the function name and parenthesis( ).

2)  Function name must be unique and follows naming rules  same as for identifiers

3)  Any input parameter should be defined within the parenthesises.

4)  A colon(:) to mark the end of function header

5)  The return statement signifies an exit of control from the function. It may or may not pass the value back to the caller function.

6)  Function can contains one or more statement to perform specific task

Function must be called/invoked to execute its code

Construct and component of a function(UDF)

        

Parameters vs Arguments:



The values being passed to function body are referred to as the arguments and the values being received as the parameters.

The number of arguments and parameters should always be equal except for the variable length list.

Arguments in Python can be one of these values types:

1) literals                                2) variables                    3) expressions

def sip(p,r,t):

    p=(p*r*t)/100

The following are some valid function call statements:

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

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

    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 :", sip(p,r,t))   # Here p, r and t are arguments

Output:

========================= RESTART: E:/Python/parameter.py ============================

Enter principal :10000

Enter rate :8

Enter time :5

Simple interest : 4000.0

RETURNING VALUES FROM FUNCTION

Functions in Python may or may not return a value. There are two types of functions in Python:

1)   Functions returning some value called non-void functions (using return keyword)

2)   Functions not returning any value called void functions

Return statement: The return statement passes the control back to the caller program (main program). It is the last statement of the function body which can also referred to as Function Terminator.

        Syntax : return <value>

Example:

def sip(p,r,t):          #Here p, r and t are parameters

    s=(p*r*t)/100

    return s              # Return outcomes to the caller program.

 

# Main Program

p=int(input("Enter principal :"))

r=float(input("Enter rate :"))

t=int(input("Enter time :"))

print("Simple interest :", sip(p,r,t))   # Here p, r and t are arguments

Features of Return Statement: Some of the features of return statement are mentioned below:

1)  It is the last statement of the function body, where the function gets terminated.

2)  No statement in the function will be executed after the return statement.

Example :

def calculate(m,n):

       add=0

       add=m+n

       return add          # here terminate the function

       p=m+n                # it is not executed

3)  A non-returnable function may or may not use return statement.

Non-returnable function with a return statement but doesn’t pass any value to the caller

Non-returnable function without return statement

def perimeter(l, w):

    result = 2 * (l + w)

    print("Perimeter of a Rectangle " = ", result) #value doesn’t return

   return

#Main Program

l = float(input('Please Enter the L of a Triangle: '))

w = float(input('Please Enter the W of a Triangle: '))

print("Perimeter of a Rectangle using", l, "and", w, = ", perimeter(l,w))

def perimeter(l, w):

    result = 2 * (l + w)

    return result           # value return

 

 

#Main Program

l = float(input('Please Enter the L of a Triangle: '))

w = float(input('Please Enter the W of a Triangle: '))

print("Perimeter of a Rectangle = ", perimeter(l,w))

 

4)  A Python function may be return multiple values to its called program(main program).

Example1:

Example2:

Example3

def multiple():

    operation = "Sum:"

    total = 5+10

    return operation, total;

 

operation, total = multiple()

print(operation, total)

----------------------------------

#Output

Sum: 15

def getPerson():

    name = "Narain Ji"

    age = 45

    country = "India"

    return name,age,country

 

name,age,country = getPerson()

print(name)

print(age)

print(country)

----------------------------------

#Output:

Narain Ji

45

India

def operation(n1,n2):

    add=n1+n2

    sub=n1-n2

    mul=n1*n2

    div=n1/n2

    return add,sub,mul,div

 

#main program

n1,n2=55,5

r1,r2,r3,r4=operation(n1,n2)

print(n1,'+',n2,'=',r1)

print(n1,'-',n2,'=',r2)

print(n1,'*',n2,'=',r3)

print(n1,'/',n2,'=',r4)

--------------------------------

#Output

55 + 5 = 60

55 - 5 = 50

55 * 5 = 275

55 / 5 = 11.0

5)  Remember: multiple return values can be returned with the help of a single return statement cannot use multiple return statements.

Example:

def operation(n1,n2):

    add=n1+n2

    sub=n1-n2


 





    return add

    return sub

    # above code use two return statements, so it will result in an error.

#Main Program

n1,n2=55,5

r1,r2=operation(n1,n2)

print(n1,'+',n2,'=',r1)

print(n1,'-',n2,'=',r2)

Modified Code:

def operation(n1,n2):

    add=n1+n2

    sub=n1-n2

    return add, sub      #or return (add, sub)

 

#Main Program

n1,n2=55,5

r1,r2=operation(n1,n2)

print(n1,'+',n2,'=',r1)

print(n1,'-',n2,'=',r2)

 

 

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

7)  Once the control exits from a function, it cannot get back into the function block for any further execution.

Example:

def Show(p):

    a=p

    for i in range(1,p):

        if (i>5):

            return i

        print(i)

 

 

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

s=Show(n)

print(s)

 

def Show(p):

    a=p

    for i in range(1,p):

        if (i>5):

            return i

        print(i)

 

 

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

s=Show(n)

print(s)

Output:

Enter a number :5

1

2

3

4

None

Output:

Enter a number :10

1

2

3

4

5

6

 Invoking/Calling a Function:

Types of values of values can be passed to a function during its innovation.

1)  Passing integer numbers to the function

2)  Passing float numbers to the function

3)  Passing string/strings to the function

4)  Passing list/lists to the function

5)  Passing tuple/tuples to the function

6)  Passing dictionaries to the function

1)  Passing integer numbers to the function:

Example: Accept two number and calculate addition and subtraction.

def calculate(n1,n2):

    add=n1+n2

    sub=n1-n2

    return add,sub

 

#Main Program

n1=int(input(“Enter a first number :”))

n2= int(input(“Enter a second number :”))

r1,r2=calculate(n1,n2)

print(n1,'+',n2,'=',r1)

print(n1,'-',n2,'=',r2)

--------------------------------

#Output

55 + 5 = 60

55 - 5 = 50

2)  Passing floating numbers to a function:

Example : To find the area and perimeter of a rectangle using function

def calculate(l,b):

    area=l*b

    pm=2*(l+b)

    return area, pm

 

#Main Program

n1=float(input(“Enter length :”))

n2= float(input(“Enter breadth :”))

ar,pr=calculate(n1,n2)

print(‘Area of rectangle :',ar)

print(‘Perimeter of rectangle :',pr)

--------------------------------

#Output

Enter the length :13.5

Enter the breadth :8.5

Area of rectangle :106.25

Perimeter of rectangle :42.0

3)  Passing string/strings to the function:

Example : Python Program to calculate the number of upper, lower and digits in a string

def count(string):  

    dc=lc=uc=0

    for i in string:

        if(i.isdigit()):

            dc=dc+1

        if (i.isupper()):

            uc=uc+1

        if (i.islower()):

            lc=lc+1

    return(dc,lc,uc)

 

#Main Program

d, l, u=count('The Quick Brown Fox12')

print("The number of digits is:", d)

print("The number of lower characters is:", l)

print("The number of upper characters is:", u)

---------------------------------------------------------

#Output

The number of digits is: 2

The number of lower characters is: 12

The number of upper characters is: 4

4)  Passing list/lists to the function

##Write a program to move all duplicate values in a list to the end of the list.

def MovDupList(l):  

    dedup = []

    dup = []

    for i in l:

        if i in dedup:

            dup.append(i)

        else:

            dedup.append(i)

    l = dedup + dup

    return(l)

#main program

l = eval(input("Enter the list: "))

print("Original List : ",l)

print("Modified List:",MovDupList(l))

Output:

Enter the list: [20, 15, 18, 15, 7, 18, 12, 13, 7]

Original List :  [20, 15, 18, 15, 7, 18, 12, 13, 7]

Modified List: [20, 15, 18, 7, 12, 13, 15, 18, 7]

5)  Passing tuple/tuples to the function

# The tuple is passed to the Function which returns the sum of elements at odd and even indices of the tuple.

def sumEvenOdd(mTuple):

    s1=s2=0

    for i in range(0,len(mTuple)):

        if i%2==0:

            s1=s1+mTuple[i]

        else:

            s2=s2+mTuple[i]

    return(s1,s2)

 

#Main Program

mTuple=eval(input("Enter a elements in tuple : "))

sumEven,sumOdd=sumEvenOdd(mTuple)

print("Sum of the elements at even indices :",sumEven)

print("Sum of the elements at odd indices :",sumOdd)

Output:

Enter a elements in tuple : (10,11,13,12,14,15,16,17,19,20)

Sum of the elements at even indices: 72

Sum of the elements at odd indices: 75

 6)  Passing dictionaries to the function
# The tuple is passed to the Function which returns the sum of elements at odd and even indices of the tuple.

def Calc(studDict):

    sum1=avg=c=0

    for key in studDict:

        sum1=sum1+studDict[key]

        c+=1

    avg=sum1/c

    return(sum1,avg)

#Main Program

studDict={'Engish':89,'Physics':98,'Chemistry':96,'Maths':100,'CS':100,'P.Ed':90}

sm,av=Calc(studDict)

print("Total Marks :",sm)

print("Percentage :",av)

Output:

Total Marks : 573

Percentage : 95.5

 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.

Example 1:                                                Example 2:                               




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)

    ar=2*(l*b+b*h+l*h)

    print("Surface Area :",ar)

 

#Main Program

Surface_Ar(b=12, h=10,l=20)

Output:

Length:  20

Breadth:  12

Height:  10

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 leftDefault arguments must be provided from right to left.


Example1:

def showInfo(name,std,roll=14): #Here, roll is assigned with default value.

    print("Roll No.:",roll)

    print("Name :", name)

    print("Class :",std)

 

#main program

showInfo('Aviral',’XII’)  # missing third argument

Output:

Roll No.: 14

Name : Aviral

Class : XII

Example2:

def showInfo(name,std='XII-A',roll=14): # Here, std and roll are assigned with default

                                                               values

    print("Roll No.:",roll)

    print("Name :", name)

    print("Class :",std)

 

#main program

showInfo('Aviral') # Here, two arguments missing

Output:

Roll No.: 14

Name : Aviral

Class : XII-A

Example3:

def showInfo(name,std='XII-A',roll=14):

    print("Roll No.:",roll)

    print("Name :", name)

    print("Class :",std)

 

#main program

showInfo('Aviral','XII-B',24)

Output:

Roll No.: 24

Name : Aviral

Class : XII-B

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.

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:

# beginning of the method

def sum(*args):

    finalResult = 0

#beginning of for loop

    for arg in args:

        finalResult = finalResult + arg

 

    return finalResult

 

#main program printing the values

print(sum(10, 20))            # 30

print(sum(10, 20, 30))        # 60

print(sum(10, 20, 2))         # 32

Output:

30

60

32

Example2:

def multiplier(*num):

    prod = 1

#initialize prod variable with zero    

    for i in num:

        prod = prod * i

 

    print("Product:",prod)

#main program

multiplier(3,5)

multiplier(1,2,4)

multiplier(2,2,6,7)

Output:

Product: 15

Product: 8

Product: 168

Example3: arguments passed as a tuple

def display(*names):

    for name in names:

        print("Welcome ", name)

    print("Welcome again ", names[3])

 

#Main Program

display("Raj","Rajan", "Aviral", "Yashu","Simmi")

Output:

Welcome  Raj

Welcome  Rajan

Welcome  Aviral

Welcome  Yashu

Welcome  Simmi

Welcome again  Yashu

Scope of variable in functions

SCOPE means in which part(s) of the program, a particular piece of code or data is accessible or known.

In Python there are broadly 2 kinds of Scopes:

Global Scope

A name declared in top level segment (main)of a program is said to have global scope and can be used in entire program.

Variable defined outside all functions are global variables.

Rules of Global variable:

1.       When we define a variable outside a function, it’s global by default. You don’t have to use global keywords.

2.       We use a global keyword to read and write a global variable inside a function.

3.       Use of global keywords outside a function has no effect.

Local Scope

A name declare in a function body is said to have local scope i.e. it can be used only within this function and the other block inside the function.

The formal parameters are also having local scope.

Rules of local variable:

1.       A variable a local scope can be accessed only within the function/block that it is created in.

2.       When a variable is created inside the function/block, the variable becomes local to it.

3.       A local variable only exists while the function is executing.

4.       The format arguments are also local to function.

Let us understand with example….

Example:

def  area(length, breadth):

                a= length*breadth          # a is local to this function

                return a

l=int(input(‘Enter Length’))

b=int(input(‘Enter Breadth’))

ar=area(l,b)                                                        # l,b and ar having global scope

print(‘Area of Rectangle =’, ar)

 

Example:

def  area(length, breadth):

                a= length*breadth          # a is local to this function

                return a

l=int(input(‘Enter Length’))

b=int(input(‘Enter Breadth’))

ar=area(l,b)                                                        # l,b and ar having global scope

print(‘Area of Rectangle =’, a)

‘a’ is not accessible  here because it is  declared in function  area(), so scope is  local to area()

Example:

def  area(length, breadth):

                a= length*breadth          # a is local to this function

                return a

 

defshowarea():

                print(‘Area of Rectangle =’, ar)

 

l=int(input(‘Enter Length’))

b=int(input(‘Enter Breadth’))

ar=area(l,b)                                                        # l,b and ar having global scope

showarea()

Variable ‘ar’ is accessible in function showarea() because  it is having Global Scope

Example:

count =0

def add(x,y):

    global count

    count+=1

    return x+y

 

def sub(x,y):

    global count

    count+=1

    return x-y

 

defmul(x,y):

    global count

    count+=1

    return x*y

 

def div(x,y):

    global count

    count+=1

    return x//y

ans=1

while ans==1:

    n1=int(input('Enter first number'))

    n2=int(input('Enter second number'))

    op=int(input('Enter 1-Add 2-Sub 3-Mul 4-Div')

    if op==1:

        print('Sum=', add(n1,n2))

elif op==2:

        print('Sub=’, sub(n1,n2))

elif op==3:

        print('Mul=', mul(n1,n2))

elif op==4:

        print('Div=’, div(n1,n2))

ans=int(input('press 1 to continue'))

print('Total operation donE', count)

This declaration “global count” is necessary for using global variables in function, otherwise an error “local variable 'count' referenced before assignment” will appear because local scope will create variable “count” and it will be found unassigned.

Lifetime of a variable is the time for which a variable lives in memory.  For Global variables the lifetime is entire program run i.e. as long as program is executing. 

For Local variables lifetime is their function’s run i.e. as long as function is executing.

 

 

No comments:

Post a Comment