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 1 + x + x^2 + ... + x^n for x = 2, n = 5 1 + 2 + 4 + 8 + 16 + 32 = 63
How it works
- The loop runs
ifrom 0 ton, and each term isx ** i. - In Python,
**means "to the power of", while^does something else entirely, so never writex ^ ifor a power. - Each term is added to
totaland also saved as text interms, so the whole series can be printed. " + ".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 + ...
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!
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises