Functions in Python:
·
A function is a
organized and reusable block of code which run when it called. In this you can
pass data which is known as parameter into the function.
·
For creating a
function use def keyword, for
example:
def function_name ( )
print(“
Hello function1”)
·
For example:
1.
To find the
factorial of given number using function in Python.
def
factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input
a number to compute the factorial : "))
print(factorial(n))
It display following output:
Input a number to compute the factorial : 4
24
2.
To find the Fibonacci
series of given number using function in Python.
def fibonacci(n):
if(n <= 1):
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input("Enter number of terms:"))
print("Fibonacci sequence:")
for i in range(n):
print(fibonacci(i))
It display following output:
Enter number of terms: 5
Fibonacci sequence:
0
1
1
2
3
No comments:
Post a Comment