Python|Find the sum of factorials from 1 to n

Problem Description

"Enter n from the keyboard to find the sum of 1+2!+3!+...+n!"

For this problem, we can define a function to solve, and then use a for loop statement to set from 1 to n, then let's write this code together.

solution

Suppose the name of this function is f


def f(x):

f =1for i inrange(1,x+1):

f *= i

return f

n =int(input("Please enter a positive integer:"))print("And as:%d“ %sum(map(f,range(1,n+1))))

If you enter a positive integer of 3, let's run it.

Figure 3.1 Running process

Note: pay attention to the use of return, can not be ignored

Conclusion

In this code, we need to know the use of the for loop statement and the definition of the def function. Note that what we require is 1 to n. According to the rule of left-closed and right-opened, we need to fill in n+1, and remember to write it after the function return. The last thing that will be printed will be an integer, so %d is needed. Pay attention to the use of symbols when writing, and do not omit them. When writing such questions, you only need to pay attention to the precautions of common codes and be more careful.

END

Recommended Posts

Python|Find the sum of factorials from 1 to n
The road to reinstallation of ubuntu 18.04 from scratch
Python implements the sum of fractional sequences
Introduction to the use of Hanlp in ubuntu
From installation to entry of FastDFS under Centos7
The tutorial for upgrading from Centos7 to Centos8 (detailed graphic)
How to turn the language of Ubuntu into Chinese? ?
How to understand the introduction of packages in Python
Solution to the slow speed of ubuntu18.04 wireless network
Python simulation to realize the distribution of playing cards