Functions are set of statements for performing a specific task. A function includes a declaration, definition and function call.
A function declaration includes a key word ‘def’ follows by a function
name and arguments.
Syntax:
def function_name(arg1,arg2,…..,argn)
where arg1…argn – arguments
Note: You can define a function without arguments also.
A function call uses the function name and arguments.
Eg: function_name(arg1,arg2,…argn)
Python program to do division of two numbers
using functions:
#first, function definition. Here,‘div’ is the function name. x,y
are the arguments. This function performs division of two numbers.
def
div(x,y):
return x/y
#Next, x and y values are read from runtime.
x
= int(input("Enter the numerator value"))
y
= int(input("Enter the denominator value"))
#The function call div(5,2) control goes to function definition. It
return the output to print statement. It prints the output.
print(div(5,2))
It gives you the following output.
A function call may contain the arguments in different order. For eg, div(x,y) is the function definition. But we call the function with different order of arguments as follows.
div(y = 3 ,x = 15)
let this function call differ from previous code.
def
div(x,y):
return x/y
print(div(y
= 3, x = 15))
The output is…
Python program to find factorial of a number using function:
Factorial is one of the important function in mathematics. It
continuously multiply a number from 1 to that number. For example, 5! = 5*4*3*2*1.
#Define the function fact with one argument ‘n’. This function uses
recursive function call. That means, a function calls itself. If the ‘n’ value
is greater than 1,it multiply and calls itself by ‘n-1’ times. Otherwise, it
returns 1.
def
fact(n):
if n >= 1 :
return n*fact(n-1)
else :
return 1
#Get the ‘n’ value from the user at run time.
n
= int(input(“Enter the number”))
#function call with ‘n’ value. Print the output.
print(“The
factorial of the given number is”, fact(n))
while executing this program, you get the below
output.
Thus the python programs using functions are briefly described with examples.
No comments:
Post a Comment