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