2016-08-17 77 views
-2

我开始学习Python,我有一小部分代码需要用户输入的阶乘。我试图理解发生了什么的逻辑,以便更好地理解过程。为什么当我改变输出变化的一个变量的位置? (我使用python 2)初学者的因子代码

user_input = input("enter a positive number") 

for i in range(user_input): 
    product = 1  #the output changes when I move it here instead of above the for loop 
    product = product * (i + 1)  
    print(product) 
+2

因为在每次循环wokr,你product'如果你这样做外循环,你之前的环跑了第一只设置'product' 1'设置为1。时间。 –

回答

1

通过将

product = 1 

内循环,要重新初始化的总价值循环的每次迭代。

如果用户要输入3, 它会显示1, 2, 3,因为每次迭代只需创建一个值为1的变量乘积并乘以(迭代器+1)即(1 *(迭代器+1))。

如果你把

product = 1 

外循环,总价值将只在开始时初始化为1,您将能够正确总结阶乘的值。

如果用户输入3作为输入一遍,它会显示1, 2, 6,因为它不再乘以(1 *(迭代器+ 1)),但(以前的总和*(迭代器+ 1))

0

如果是在循环,这意味着每次循环迭代,产品将向1.所以,你最终获得相同的结果,如果你跑了刚刚被重置循环的最终迭代。换句话说,产品不会积累。

0

这是因为每一次的循环运行,你设置:

产品= 1个

0

产品是在循环的每个迭代复位为1。

1

环路是这样的:

user_input = input("enter a positive number") 

for i in range(user_input): 
    product = 1     #Set product to 1 
    product = product * (i + 1) #Increase product 
    print(product)    #Print the product 

每个循环的product值将做计算之前重置回1

回路1
产物= 1
产物= 1 *(1 + 1)= 2
回路2
产物= 1
产物= 1 *(1 + 2)= 3

1

这个心不是要回答你的问题......但我发现阶乘是最容易想到递归

def factorial(n): 
    #base case if n is 0 or 1 : 0! == 1! = 1 
    if n in (1,0): return 1 
    #recursive case : otherwise n! == n*(n-1)! 
    return n*factorial(n-1) 
0

我认为这是你想要做的。

user_input = int(input("enter a positive number")) 
product = 1 
for i in range(user_input): 
    product = product * (i + 1)  
    print(product) 

但是当你把产品= 1进入循环,每次循环开始产品= 1,它删除以前的生产。这样

user_input = int(input("enter a positive number")) 
for i in range(user_input): 
    product = i + 1 
    print(product)