Skip to main content

User Defined Functions in Python

So far we have only seen the functions which come with Python either in some file (module) or in interpreter itself (built in), but it is also possible for programmer to write their own function(s) and are called User Defined Functions. These functions can then be combined to form a module which can then be used in other programs by importing them.

In the context of programming, a function is a named sequence of statements that performs a desired operation. This operation is specified in a function definition.

To define a function keyword def is used. After the keyword comes an identifier i.e.name of the function, followed by parenthesized list of parameters and the colon which ends up the line. Next follows the block of statement(s) that are the part of function.
A block is one or more lines of code, grouped together so that they are treated as one big sequence of statements while executing. In Python, statements in a block are written with indentation. Usually, a block begins when a line is indented (by four spaces) and all the statements of the block should be at same indent level.

The following are the two simple reasons to write a function
·        Creating a new function gives you an opportunity to name a group of statements. Functions can simplify a program by hiding a complex computation behind a single command.
·       Creating a new function can make a program smaller by eliminating repetitive code.

Syntax of function is:
#Square brackets include optional part of statement

def  functionname ([parameter1, parameter2, …..]):
statement(s) block
[return value]
           
Function header
            It begins with the keyword def and ends with colon and contains the function identification details such as name and parameters passed.
Function body
Consisting of sequence of indented Python statement(s), to perform a task. The body of the function gets executed only when the function is called/invoked.

Function Call
Function call contains the name of the function (being executed) followed by the list of values (i.e. arguments) in parenthesis. These arguments are assigned to parameters. When the function is returning a value we can assign the function call statement to a variable.
#a void function which does not return any value. No parameters are also passed.
def printname(): # function header
            print “Hi I am Binu” #function body

printname() # function call
#function with both argument and return value.
#a document string in triple quotes is also included which can be used for help
def area (radius):      #function header
“”” Calculates area of a circle.                                           docstring begins

require an integer or float value to calculate area.
returns the calculated value to calling function “””      docstring ends
            a=3.14*radius**2
return a

a=area(5) #function call
a=area(2.3)
Flow of execution
Execution always begins at the first statement of the program. Statements are executed one at a time, in order from top to bottom. Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is called. Although it is not common, you can define one function inside another.In this case, the inner definition isn’t executed until the outer function is called.
Function calls are like a detour in the flow of execution. Instead of going to the next statement, the flow jumps to the first line of the called function, executes all the statements there, and then comes back to pick up where it left off. This will happen in the case of nested functions also.
Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of execution.
Parameters and Arguments
Parameters are the value(s) provided in the parenthesis when we write function header.These are the values required by function to work. radius is a parameter to function area.If there is more than one value required by the function to work on, then, all of them will be listed in parameter list separated by comma.

Arguments are the value(s) provided in function call/invoke statement. List of arguments should be supplied in same way as parameters are listed. Bounding of parameters to arguments is done 1:1, and so there should be same number and type of arguments as mentioned in parameter list.

Default value to parameters
It is possible to provide parameters of function with some default value. In case the user does not want to provide values (argument) for all of them at the time of calling, we can provide default argument values.
Example
def greet (message,times=1):
print message * times
greet (‘Welcome) # calling function with one argument value
greet (‘Hello, 2) # calling function with both the argument values.

Local and Global variables
Local variables are created and used inside a function and is local to that function. The variable cannot be accessed outside the function.
Global variables are defined outside the function, which can be used in any functions.However you can access the global variable by defining it as global inside the function.

The following example illustrate this
Local Variables
def f():
            x=10
            print x
f() # this will print 10
print x # this will print error because x is a local variable not available outside the function.

Global Variables
X=10
def inc():
            global X
            X=X+1
def dec():
            global X
             X=X-1
print X  # this will print 10
inc()
print X # this will print 11
dec()
dec()
print X #this will print 9

Sample programs using functions

Write a python function to find the area of a circle.(University Question)
def circlearea (radius):      
      area=3.14*radius**2
      return area
#function call
circlearea(5)
Write a Python program using function to convert an integer to a string.
def intstring(n):
  return str(n)

n=input("Enter a number...")
s=intstring(n)
print s, type(s)

Menu driven program to implement arithmetic operations using functions.

def add(a,b):
    print "Sum=",a+b
def sub(a,b):
    print "Diff=",a-b
def mul(a,b):
    print "Product=",a*b
def exp(a,b):
    print "Exponent=",a**b
while True:
     print "\n....Menu...\n1.Sum\n2.Diff\n3.Product\n4.Exponent\n5.exit\n"
     ch=input("Enter your choice")
     if ch==5:
         break
     a=input("Enter first number..")
     b=input("Enter second number..")
     if ch==1:
         add(a,b)
     if ch==2:
         sub(a,b)
     if ch==3:
         mul(a,b)
     if ch==4:
         exp(a,b)
Program to compute nCr using a separate function to compute factorial.
def fact(n):
    f=1
    for i in range(1,n+1):
        f=f*i
    return f

print "Program to compute nCr..."
n=input("Enter n..")
r=input("Enter r...")
ncr=fact(n)/(fact(n-r)*fact(r))
print "nCr...",ncr
Finding BCD of a decimal number….
def binary(d):
    bd=""
    while d!=0: # finding binary of each digit
        b=d%2
        bd=str(b)+bd
        d=d/2
    l=4-len(bd)
    for i in range(l): # filling rest of the bits with 0
        bd="0"+bd
    return bd
n=input("Enter n..")
bcd=""
while n!=0: # taking each digit and finding binary
    d=n%10
    bcd=binary(d)+","+bcd
    n=n/10
print "BCD....",bcd
Functions to check whether the character passed is a letter or digit
import string
def isdigit(c):
            return c in string.digits
def isletter(c):
            return c in string.letters
c=raw_input(“Enter a character”)
print isdigit(c)
print isletter(c)
Generating first N prime numbers using a function is_prime(n), which will check whether n is prime or not.
def is_prime(n):
    i=2
    while i<=n/2:
        if n%i==0:
            return False
        i=i+1
    else:
        return True
N=input("how many prime numbers you want...")
i=0
p=2
while i<N:
   if is_prime(p) :
       print p
       i=i+1
   p=p+1
Generating first N Fibonacci numbers
def fib(N):
    a=0
    b=1
    i=2
    print a,b,
    while i<N:
        c=a+b
        print c,
        a,b=b,c
        i=i+1
N=input("how many Fibonacci numbers you want...N>=2....")

fib(N)
First N Fibonacci numbers as list ( university question)
def fib(N):
    fiblist=[0,1]
    i=2
    a=0
    b=1
    while i<N:
        c=a+b
        fiblist.append(c)
        a,b=b,c
        i=i+1
    return fiblist  

N=input("how many Fibonacci numbers you want...N>=2")
fiblist=fib(N)
print fiblist
Write a Python program to print the odd composite numbers between m and n, where m and n are positive integer greater than 1.( University Question)
def compost(x):
    for i in range(2,x/2+1):
        if x%i==0:
            return 1
    else:
        return 0
m=input('Enter m  ')
n=input('Enter n  ')
for i in range(m+1,n):
    if i%2!=0:
        if compost(i)==True:
            print i
Menu driven program to implement the following i)check even or odd ii)check number is positive negative or zero iii) generate factors of a number ( University Question)
def evenodd(n):
    if n%2==0:
        print "even"
    else:
        print "odd"
def postvnegtv(n):
    if n>0:
        print "+ve"
    elif n<0:
        print "-ve"
    else:
        print "zero"
def factors(n):
    print "factors"
    for i in range(1,n+1):
        if n%i==0:
            print i,
while True:
     print "\n....Menu...\n1.even or odd\n2.postv or negtv \n3.factors\n4..exit\n"
     ch=input("Enter your choice---")
     if ch==4:
         break
     n=input("Enter a number..")
     if ch==1:
         evenodd(n)
     if ch==2:
         postvnegtv(n)
     if ch==3:
         factors(n)
Python function to extract digits and checks whether all the digits are even(university question)
def digit(n):
   flag=1
   while n!=0:
      d=n%10
      if d%2!=0:
         flag=0
         break
      n=n/10
   return flag

n=input("Enter a number::")
if digit(n):
        print "all digits are even"
else:
        print "all digits are not even"
Now you can write the following programs using simple functions
1.Write a function big(a,b) which will print the biggest of two number.
2.Write a python function to find the area of a circle.( university question)
3.Write a program asks users for the temperature in Fahrenheit (F) and prints the temperature in Celsius. (Conversion: Celsius = (F - 32) * 5/9.0). Use a function convert which takes one argument F and returns C.
4. Write a Python function, odd, that takes in one number and returns True when the number is odd and False otherwise.
5. Write a Python function, fourthPower( ), that takes in one number and returns that value raised to the fourth power.
6.Write a menu driven Python program to simulate a calculator with addition, subtraction, multiplication, division and exponentiation. Use separate function to implement each operation.( university question)
7.Write a program to compute nCr, using a factorial function.(university question)
8.Write a Python program to calculate the area of a circle, given the center and a point on the perimeter. Use a function to find the radius as the distance between two points.(university question)
9. Write a function to find the sum of numbers between a lower bound and an upper bound.( university question)
10.Write a Python program using function to check the type of a triangle(scalene, isosceles, equilateral) by getting the vertices from the user.( university question)
11.Find the binary equivalent of each digit of a number(ie;BCD each digit is represented as 4 bit binary). Use a separate function to find binary.
12.Write a menu driven program to calculate area of a circle, triangle,rectangle and square.Use separate function to implement each operation.( University question)
13.Write a program to display a multiplication table of size nxn for any given 'n' using function.( university question)
14.Write two functions isdigit(), which returns true if the character passed is a digit and isletter() ,which return true if the character passed is a letter.( university question).
15.Write a program that reads an integer N from the keyboard and then calls a user defined function to compute and displays the sum of numbers from N to 2N if N is non-negative. If N is negative display the sum from 2N to N. The starting and end points are included in the sum.(university question)
16.Write a python function that will accept three arguments x,y and z.Find x+y and if the sum is greater than z, return the square root of (x^2+y^2), otherwise return -1.(university question)
17.Find the sum of the series 1-x^2/2!+x^4/4!-x^6/6!......n terms.Use a function fact to find the factorial of the number( university question).
18.Write a Python function is_prime(n), which returns True if he number n is a prime and returns False, if the number n is not prime.Use the is_prime(n) function to generate first N prime numbers.(university question)
19.Write a python function to generate first N Fibonacci numbers and return as a list.(university question)
20.Write a python function digit() to extract digit of a number. Check whether all the digits are even.

Comments

  1. Well Done ! the blog is great and Interactive it is aboutWell Done ! the blog is great and Interactive it is about How to consolidate Microsoft Excel Worksheets in VBA? it is useful for students and Python Developers for more updates on python

    python online course



    ReplyDelete
  2. Thank you for posting such nice blog.Basic tasks can be completed by using Python codes in a most reliable way as it requires less time and space. Find more details on Python Course in Noida

    ReplyDelete
  3. Thanks for the good words! Really appreciated. Great post. I’ve been commenting a lot on a few blogs recently, but I hadn’t thought about my approach until you brought it up. 
    Microsoft Azure online training
    Selenium online training
    Java online training
    Java Script online training
    Share Point online training

    ReplyDelete
  4. Really its amazing post and thank you for sharing this post.
    Visit https://www.pythontraining.net/

    ReplyDelete
  5. Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work.



    mobile phone repair in Novi
    iphone repair in Novi
    cell phone repair in Novi
    phone repair in Novi
    tablet repair in Novi
    ipad repair in Novi
    mobile phone repair Novi
    iphone repair Novi
    cell phone repair Novi
    phone repair Novi

    ReplyDelete
  6. very informative blog and useful article thank you for sharing with us, keep posting learn more Technology
    Python Training in Electronic City

    ReplyDelete
  7. Thank you for the sharing this resourceful guidance here. Keep blogging.
    Python Online Training

    ReplyDelete
  8. Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging. After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.

    Power Bi Training in GUrgaon
    SQL Training in Gurgaon
    Advanced Excel /VBA training in Gurgaon
    Tableau Training in Gurgaon

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. Got some wonderful knowledge from this post. I got some great information from the article you've published during this post. Keep Posting. python course in delhi

    python training in delhi

    ReplyDelete

Post a Comment

Popular posts from this blog

Classes and Objects in Python

Python is an object-oriented programming language, which means that it provides features that support object-oriented programming. The basic components of object oriented programming are classes and objects. A Class is a blue print to create an object. It provides the definition of basic attributes and functions of objects. Object is a running instance of the class having the identity(name), properties( values) and behaviors(functions). The Object oriented program thus consist of object definitions (classes) and most of the computations and functions are mentioned as operations on the object. Each object definition corresponds to some object or concept in the real world, and the functions that operate on these object correspond to the ways real-world objects interact. We have learned objects of string, list, tuple etc…and used the properties and functionalities of these objects which are built into the Python. Now we are going to create our own(user defined) objects. Th

Identifiers,Variables and Keywords

Identifiers An identifier is a name given to entities like variables,functions,class, functions etc. It helps to differentiate one entity from another. Rules for writing identifiers 1.Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _.  Names like myClass, var_1 and print_this_to_screen, all are valid example. 2.An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name. 3.Keywords cannot be used as identifiers. Eg: global = 1 is invalid 4.We cannot use special symbols like !, @, #, $, % etc. in our identifier. a@=0 is invalid 5.An identifier can be of any length. Things to Remember Python is a case-sensitive language. This means, Variable and variable are not the same. Always give the identifiers a name that makes sense. While c = 10 is a valid name, writing count=10 would make more sense, and it would be easier to figure out what it represents when you look at your code after

Files in Python , Exception handling

While a program is running, its data is in main memory. When the program ends, or the computer shuts down, data in memory disappears. To store data permanently, you have to put it in a file. Files are usually stored on a secondary storage device(hard disk, pen drive, DVD,CD etc).  When there are a large number of files, they are often organized into directories (also called “folders”). Each file is identified by a unique name, or a combination of a file name and a directory name.  By reading and writing files, programs can exchange information with each other and generate printable formats like PDF. Working with files is a lot like working with books. To use a book, you have to open it. When you’re done, you have to close it. While the book is open, you can either write in it or read from it. In either case, you know where you are in the book. Most of the time, you read the whole book in its natural order, but you can also skip around. All of this applies to files as well.