How to realize the Sum of factorials in Python
This article is about how Python implements the sum of factorial. Xiaobian thinks it is quite practical, so share it with everyone for reference. Let's follow Xiaobian and have a look.
code implementation
Sum=0factorial=1num = int(input ('please input a number'))for i in range(1,num+1): factorial = factorial*i print ('output loop factorial intermediate process value', factorial) Sum +=factorialprint ('sum of factorial: ',Sum)
Output:
Please enter a number: 5
Intermediate process value of output loop factorial value: 1
Intermediate process value of output loop factorial value: 2
Intermediate process value of output loop factorial value: 6
Intermediate process value of output loop factorial value: 24
Intermediate process value of output loop factorial value: 120
Sum of factorial: 153
program analysis
Factorial: Also a term used in mathematics; factorial refers to the multiplication of 1 by 2 by 3 by 4 up to the desired number; when expressing factorial, use "! "To show. If h factorial, then h!; Factorial is generally difficult to calculate because the products are large.
The sum of factorial, i.e. the sum of all factorial of numbers before h
Line 1 and line 2 initialize variables, Sum is used to record the sum of factorial, factorial is used to record the value of factorial
Line 3 of the program prompts the user to enter the number of factorial sums required
Lines 4 through 7 sum factorial products through a for loop. Line 4, the range(1,num+1) of the for loop limits the factorial range from 1 to num, line 5 records the factorial of the variable i, factorial always records the factorial of i-1, line 6 deliberately outputs the middle of the factorial value, and line 7 records the sum of factorial values from 1 to num. Finally, the program outputs the sum of factorial.
Thank you for reading! About "Python how to achieve the sum of factorial" this article is shared here, I hope the above content can be of some help to everyone, so that everyone can learn more knowledge, if you think the article is good, you can share it to let more people see it!