0% found this document useful (0 votes)
3 views

Recursion Examples Python

The document contains Python functions for various mathematical and string operations, including calculating the factorial of a number, generating Fibonacci series, summing natural numbers, reversing a string, and computing the power of a number. Each function is demonstrated with a print statement showing its output. The functions utilize recursion to achieve their results.

Uploaded by

shobithap088
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Recursion Examples Python

The document contains Python functions for various mathematical and string operations, including calculating the factorial of a number, generating Fibonacci series, summing natural numbers, reversing a string, and computing the power of a number. Each function is demonstrated with a print statement showing its output. The functions utilize recursion to achieve their results.

Uploaded by

shobithap088
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

1.

Factorial of a Number

------------------------

def factorial(n):

if n == 0 or n == 1:

return 1

return n * factorial(n - 1)

print("Factorial of 5:", factorial(5))

2. Fibonacci Series

-------------------

def fibonacci(n):

if n <= 1:

return n

return fibonacci(n - 1) + fibonacci(n - 2)

print("Fibonacci number at position 6:", fibonacci(6))

3. Sum of Natural Numbers

-------------------------

def sum_natural(n):

if n == 1:

return 1

return n + sum_natural(n - 1)
print("Sum of first 10 natural numbers:", sum_natural(10))

4. Reverse a String

-------------------

def reverse_string(s):

if len(s) == 0:

return s

return reverse_string(s[1:]) + s[0]

print("Reversed string:", reverse_string("hello"))

5. Power of a Number (a^b)

--------------------------

def power(a, b):

if b == 0:

return 1

return a * power(a, b - 1)

print("2 raised to power 4 is:", power(2, 4))

You might also like