1 #题目: Beg for 1+2!+3!+...+20! 's and.
Code:
2 3 m = 0 4 for x in range (1,21): 5 s = 1 6 for y in range (1,x+1): 7 s *= y 8 m + = s 9 pri NT (' 1+2!+3!+...+20! ' and%d '%m)
Operation Result:
[[email protected] code_100]# python code_25.py 1+2!+3!+...+20! and for 2561327494111820313[[email protected] code_100]#
Code Explanation:
#思路: The factorial value of each number is calculated first, and then the sum of all the factorial values is calculated and 2 3 m = 0 #m是求和累加, initialized to 0 4 for x in range (1,21): #遍历1到20个数 5 s = 1 #s是求累乘, initialized to 1, the position should be placed in the middle of the two for loop, each time the inner for loop is completed, the next for x start calculation will be reset 1 6 for y in range (1,x+1): #这个for The value of y is from 1 to X, which contains the values of all factorial 7 s *= y #将所有符合要求的数字相乘, you get the value of the factorial of the for x number 8 m += s #将这20个数的所有的阶乘值相加 to get the final result 9 print (' 1+2!+3!+...+20! ' and%d '%m ') #打印这20个数的阶乘的和
This article is from the "Learning Notes" blog, so be sure to keep this source http://netsyscode.blog.51cto.com/6965131/1748652
"Python" programming language Introduction Classic 100 cases--25