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 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
return a

a=area(5) #function call
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.
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():
            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
def inc():
            global X
def dec():
            global X
print X  # this will print 10
print X # this will print 11
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):      
      return area
#function call
Write a Python program using function to convert an integer to a string.
def intstring(n):
  return str(n)

n=input("Enter a number...")
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:
     a=input("Enter first number..")
     b=input("Enter second number..")
     if ch==1:
     if ch==2:
     if ch==3:
     if ch==4:
Program to compute nCr using a separate function to compute factorial.
def fact(n):
    for i in range(1,n+1):
    return f

print "Program to compute nCr..."
n=input("Enter n..")
r=input("Enter r...")
print "nCr...",ncr
Finding BCD of a decimal number….
def binary(d):
    while d!=0: # finding binary of each digit
    for i in range(l): # filling rest of the bits with 0
    return bd
n=input("Enter n..")
while n!=0: # taking each digit and finding binary
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):
    while i<=n/2:
        if n%i==0:
            return False
        return True
N=input("how many prime numbers you want...")
while i<N:
   if is_prime(p) :
       print p
Generating first N Fibonacci numbers
def fib(N):
    print a,b,
    while i<N:
        print c,
N=input("how many Fibonacci numbers you want...N>=2....")

First N Fibonacci numbers as list ( university question)
def fib(N):
    while i<N:
    return fiblist  

N=input("how many Fibonacci numbers you want...N>=2")
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
        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"
        print "odd"
def postvnegtv(n):
    if n>0:
        print "+ve"
    elif n<0:
        print "-ve"
        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:
     n=input("Enter a number..")
     if ch==1:
     if ch==2:
     if ch==3:
Python function to extract digits and checks whether all the digits are even(university question)
def digit(n):
   while n!=0:
      if d%2!=0:
   return flag

n=input("Enter a number::")
if digit(n):
        print "all digits are even"
        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.


  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

  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

  3. Great post. Thank you for sharing such useful information. Please keep sharing
    Python Course in Delhi

  4. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
    Python Training in Bangalore

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

  6. It has been simply incredibly generous with you to provide openly what exactly many individuals would’ve marketed for an eBook to end up making some cash for their end, primarily given that you could have tried it in the event you wanted.
    linux Training in Chennai | Best linux Training in Chennai
    Unix Training in Chennai | Best Unix Training in Chennai
    Sql Training in Chennai | Best Sql Training in Chennai
    Oracle Training in Chennai | Best Oracle Training in Chennai
    Digital Marketing Training in Chennai | Best Digital Marketing Training in Chennai


Post a Comment

Popular posts from this blog

Strings in Python

Strings are compound data type made of sequence of characters. Hence from the string, the individual charters can also be directly accessed. Strings are created by using single quotes or double quotes or triple quotes.
>>>s1="Python Programming"
>>>s2='Python Programs'
>>>s3="""Python is a powerful
Programming language"""

This will create a string object s1, s2 and s3 using different forms.
Individual characters can be accessed using different subscripts( +ve or –ve) with the string object.
We can also slice a string. Segment of a string is called a slice.
If the first index is not mentioned, the slicing will start from 0.
If the last index is not mentioned, the …

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. The class provides basic…

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. 
To open a…