任何人都可以帮我这个python函数?新手,我不知道它是如何工作的

时间:2015-04-16 02:49:50

标签: python

def mystery(x):                 # line 1
    answer = 1                  # line 2
    while x > 0:                # line 3
        answer = x * answer     # line 4
        x = x-1                 # line 5
    return answer               # line 6
                                # line 7
value = 4                       # line 8
print(mystery(value))           # line 9 

显然它打印24,但我不知道这是怎么回事。

3 个答案:

答案 0 :(得分:1)

迭代1:

x = 4, answer = 1
answer = 4 * 1 --> answer = 4
x = x - 1 --> x = 3

迭代2:

x = 3, answer = 4
answer = 3 * 4 --> answer = 12
x = x - 1 --> x = 2

迭代3:

x = 2, answer = 12
answer = 2 * 12 --> answer = 24
x = x - 1 --> x = 1

迭代4:

x = 1, answer = 24
answer = 1 * 24 --> answer =  24
x = x - 1 --> x = 0

现在x不是> 0因此迭代停止。

答案 1 :(得分:1)

第8行将4作为参数传递给mystery函数。在mystery函数中:

1)代码以x的{​​{1}}开头,然后乘以4,即answer。答案设置为此值1。从4中减去1x现在是x

2)3x乘以3answer从步骤1获得4。从12中减去1x现在是x

3)2x乘以2answer从步骤2获得12。从24中减去1x现在是x

4)1x乘以1answer从步骤3获得24。从24中减去1x现在是x0不再超过x,导致0停止。

现在代码loopprint函数返回的值,从第4步开始mystery

简而言之,代码正在执行24,等于4 * 3 * 2 * 1

答案 2 :(得分:0)

它是阶乘的。 4! = 24.它实际上是吹4!输出到4x3x2x1,从x开始,递减1,再乘以现有的答案,直到x为0。