Here,We are going to write python program to input the value of x and n and print the sum of series :1-x + x² – x³ + … + xⁿ. We can print the sum of series by using if-else loop or we can use for loop to print the sum of above series.
Python program to print series using if-else loop
x = int(input("Enter the value of x : "))
n = int(input("Enter the value of n : "))
sum = 0
for i in range(n+1):
if(i%2 == 0):
sum = sum+(x**i)
else:
sum = sum-(x**i)
print("Sum of Series is :",sum)
Output
Enter the value of x : 4 Enter the value of n : 6 Sum of Series is : 3277
Python program to print series without using if-else loop
#without using if else loop
x = int(input("Enter the value of x : "))
n = int(input("Enter the value of n : "))
sum = 0
for i in range(n+1):
sum = sum + ((-1)**i)* (x**i)
print("Sum of Series is :",sum)
Output
Enter the value of x : 2 Enter the value of n : 8 Sum of Series is : 171
<