Search code examples
pythonpython-3.xfor-loopsequencenested-for-loop

Write a Python program to print the following sequence of numbers (N to be entered by user): X + X^2/2! + X^3/3!+... Upto Nth Term


The question has already been mentioned. I have written a code for it, and i am not getting the desired output. We don't have to actually find the sum, only display all the individual addends, and that is the part i am having trouble with.

Here is the code I have written:

x = int(input("Please enter the base number: "))
n = int(input("Please enter the number of terms: "))
s = 0
factorial = 1
for j in range(1,n+1):
    factorial = factorial*j
    for i in range(x,n+1):
        s = (x**i)/factorial
        print(s,end='+')

My output is coming:

Please enter the base number: 2
Please enter the number of terms: 5
4.0+8.0+16.0+32.0+2.0+4.0+8.0+16.0+0.6666666666666666+1.3333333333333333+2.6666666666666665+5.333333333333333+0.16666666666666666+0.3333333333333333+0.6666666666666666+1.3333333333333333+0.03333333333333333+0.06666666666666667+0.13333333333333333+0.26666666666666666+

which is obviously not the answer i am looking for. My desired output would be something like this:

Please enter the base number: 2
Please enter the number of terms: 5
2.0+2.0+1.33333+0.66667+0.26667+

What changes should i make within the code to get the required results?

  • Side note: I am working on a Mac with Python version 3.8.5

Solution

  • You don't need two loops. You only need one loop because your series is generalized to x**n/factorial(n) and you only want to increment the value of n.

    x = 2 # int(input("Please enter the base number: "))
    n = 5 # int(input("Please enter the number of terms: "))
    s = 0
    factorial = 1
    for i in range(1,n+1):
        factorial = factorial*i
        s = (x**i) / factorial
        print(s, end='+')
    

    This prints:

    2.0+2.0+1.3333333333333333+0.6666666666666666+0.26666666666666666+
    

    Of course, if you want to format the numbers to a fixed number of decimal places, specify that using a f-string:

    for i in range(1,n+1):
        factorial = factorial*i
        s = (x**i) / factorial
        print(f"{s:.6f}", end='+')
    
    2.000000+2.000000+1.333333+0.666667+0.266667+