Editor

Python Program to Find the Sum of a Series

Intermediate · Numbers · CBSE class 11 practical list

This program adds up the series 1 + x + x^2 + x^3 + ... + x^n for given values of x and n. Each term is x raised to a power one higher than the term before, starting from x^0, which is 1.

Program

sum_of_series.py
x = 2 # or: x = int(input("Enter the value of x: "))
n = 5 # or: n = int(input("Enter the value of n: "))
total = 0
terms = []
for i in range(n + 1):
term = x ** i # x to the power i
total += term
terms.append(str(term))
print(f"Sum of 1 + x + x^2 + ... + x^n for x = {x}, n = {n}")
print(" + ".join(terms), "=", total)
Output
Sum of 1 + x + x^2 + ... + x^n for x = 2, n = 5
1 + 2 + 4 + 8 + 16 + 32 = 63

How it works

  1. The loop runs i from 0 to n, and each term is x ** i.
  2. In Python, ** means "to the power of", while ^ does something else entirely, so never write x ^ i for a power.
  3. Each term is added to total and also saved as text in terms, so the whole series can be printed.
  4. " + ".join(terms) puts " + " between the terms to show the working, like 1 + 2 + 4.

Other ways to write it

Alternating signs: 1 - x + x^2 - x^3 + ...

Alternating signs: 1 - x + x^2 - x^3 + ...
x = 2
n = 5
total = 0
for i in range(n + 1):
sign = (-1) ** i # +1, -1, +1, -1, ...
total += sign * x ** i
print(f"Sum of 1 - x + x^2 - ... for x = {x}, n = {n}:", total)
Output
Sum of 1 - x + x^2 - ... for x = 2, n = 5: -21

(-1) ** i is 1 when i is even and -1 when i is odd, which flips the sign of every other term.

With factorials: x + x^2/2! + ... + x^n/n!

With factorials: x + x^2/2! + ... + x^n/n!
x = 2
n = 5
total = 0
factorial = 1
for i in range(1, n + 1):
factorial *= i # i! = (i - 1)! times i
total += x ** i / factorial
print(f"Sum of x + x^2/2! + ... + x^n/n! for x = {x}, n = {n}:", round(total, 4))
Output
Sum of x + x^2/2! + ... + x^n/n! for x = 2, n = 5: 6.2667

The factorial is built up one step at a time in the same loop, instead of being worked out again from scratch for every term.

Try it yourself

Set x = 3 and n = 4, and check the answer by hand: 1 + 3 + 9 + 27 + 81 = 121.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises