Monday, June 5, 2023

#PYTHON(DAY40)Example Programs

 

#PYTHON(DAY40)

Example programs

1) Python Program to Display Fibonacci Sequence Using Recursion

# Python program to display the Fibonacci sequence

def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = 10

# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))

And the output is:

Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34

2) Python Program to Find Sum of Natural Numbers Using Recursion

# Python program to find the sum of natural using recursive function

def recur_sum(n):
if n <= 1:
return n
else:
return n + recur_sum(n-1)

# change this value for a different result
num = 16

if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))

And the output is:

The sum is 136

3) Python Program to Find Factorial of Number Using Recursion

# Factorial of a number using recursion

def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)

num = 7

# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))

And the output is:

The factorial of 7 is 5040

No comments:

Post a Comment

Building Static Website(part6) HTML Lists

  Building Static Website (part6) HTML Lists Today, let us add some lists to our detailed view section by using html lists. Lists: List is a...