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.

**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)

**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)

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)

**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

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

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)

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)

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

ReplyDeletepython online course

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

ReplyDeleteGreat post. Thank you for sharing such useful information. Please keep sharing

ReplyDeletePython Course in Delhi

I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.

ReplyDeletePython Training in Bangalore