26
Question Write a recursive function to add the first 'n' terms of the series:
1 + 1/2 - 1/3 + 1/4 - 1/5...............
def add_series_terms(n):
if n == 1:
return 1
elif n % 2 == 0:
return add_series_terms(n - 1) + 1 / n
else:
return add_series_terms(n - 1) - 1 / n
n = int(input("Enter the term: "))
print(add_series_terms(n))Enter the term: 2
1.5
Enter the term: 5
1.2166666666666668
def
add_series_terms
(
n
):
if
n
==
1
:
return
1
elif
n
%
2
==
0
:
return
add_series_terms
(
n
-
1
)
+
1
/
n
else
:
return
add_series_terms
(
n
-
1
)
-
1
/
n
n
=
int
(
input
(
"Enter the term: "
))
print
(
add_series_terms
(
n
))
Output
Enter the term: 2
1.5
Enter the term: 5
1.2166666666666668