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)
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)
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)
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"
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.
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)
20.Write a python function digit() to extract digit of a number. Check whether all the digits are even.
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.
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
ReplyDeleteThanks 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.
ReplyDeleteMicrosoft Azure online training
Selenium online training
Java online training
Java Script online training
Share Point online training
Really its amazing post and thank you for sharing this post.
ReplyDeleteVisit https://www.pythontraining.net/
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.
ReplyDeletemobile 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
very informative blog and useful article thank you for sharing with us, keep posting learn more Technology
ReplyDeletePython Training in Electronic City
This information is really awesome thanks for sharing most valuable information.
ReplyDeletePython Online Training in Hyderabad
Python Training in Hyderabad
Python Training
Python Online Training
Nice article with lot of valuable information. keep rocking.
ReplyDeleteAngularJS training in chennai | AngularJS training in anna nagar | AngularJS training in omr | AngularJS training in porur | AngularJS training in tambaram | AngularJS training in velachery
Thank you for the sharing this resourceful guidance here. Keep blogging.
ReplyDeletePython Online Training
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.
ReplyDeletePower Bi Training in GUrgaon
SQL Training in Gurgaon
Advanced Excel /VBA training in Gurgaon
Tableau Training in Gurgaon
ReplyDeleteTHE GREAT POST
THANKS FOR SHARING
R Programming Training in Delhi SASVBA
VBA course in Delhi SASVBA
Full Stack Course in Delhi SASVBA
SASVBA
GMB
FOR MORE INFO:
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteGot 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
ReplyDeletepython training in delhi
perde modelleri
ReplyDeletesms onay
TURKCELL MOBİL ÖDEME BOZDURMA
Nft Nasil Alınır
Trafik Sigortasi
DEDEKTÖR
SİTE KURMAK
ASK ROMANLARİ
kartal vestel klima servisi
ReplyDeletebeykoz bosch klima servisi
ümraniye samsung klima servisi
kartal mitsubishi klima servisi
ümraniye mitsubishi klima servisi
beykoz vestel klima servisi
üsküdar mitsubishi klima servisi
çekmeköy vestel klima servisi
ümraniye vestel klima servisi