Write a program to input the value of x and n and print the sum of the following series: X-X²/2+X³/3-X⁴/4+........Xn/n

x=float(input('enter the value of x'))
n=int(input('enter value of n'))
sum=0
for n in range(1,n+1):
  if(n%2==0):
    sum=sum-(1*(x**n))/n
else:
    sum=sum+(1*(x**n))/n
 print('sum of series is ',sum)

 

Explanation: A mathematical series is given here and we have to put logic according to it. If we take a close look at series, at odd location we have positive sign and at even positions of variable we have negative sign. So we have decided to put our logic according to that.

First we took a float value for variable x from user. Float function converts the string input of input function to floating values. After that we took value of n(power) upto which variable series will go on and calculate the sum. Sum variable is initialized to value 0 and then a loop is started for the value 1 to n using range function.

If n modulus 2 not produces any remainder, it means we are adding values for even locations and we have to subtract that variable value calculation from total sum. Modulus operator returns remainder of division operation.

 Otherwise we have to add variable value calculation at odd location to the total sum. in this way loop will continue upto value of n and calculate according to if else logic. Finally when loop completes its repetition of code execution program prints the sum of series by sum variable.