我还没有得到循环的概念。我得到以下代码:
x=0
while x < n:
x = x+1
print x
打印 1,2,3,4,5。
很好,但是我如何访问在循环中完成的计算?例如,如何返回循环的乘积(5*4*3*2*1)?
谢谢。
编辑:
那是我的最终代码:
def factorial(n):
result = 1
while n >= 1:
result = result *n
n=n-1
return result
我还没有得到循环的概念。我得到以下代码:
x=0
while x < n:
x = x+1
print x
打印 1,2,3,4,5。
很好,但是我如何访问在循环中完成的计算?例如,如何返回循环的乘积(5*4*3*2*1)?
谢谢。
编辑:
那是我的最终代码:
def factorial(n):
result = 1
while n >= 1:
result = result *n
n=n-1
return result
通过存储该产品并返回该结果:
def calculate_product(n):
product = 1
for x in range(n):
product *= x + 1
return product
现在我们有一个函数可以产生你的计算,并返回结果:
print calculate_product(5)
您想再引入一个变量 ( total),其中包含一系列操作的累积值:
total = 1
x = 1
while x <= 5:
total *= x
x += 1
print x, total
print 'total:', total
实际上,更pythonic的方式:
total = 1
n = 5
for x in xrange(1, n + 1):
total *= x
print total
请注意, 的初始值total必须是1而不是0,因为在后一种情况下,您将始终收到0结果(0*1*..始终等于0)。
一个“单线”
>>> import operator
>>> reduce(operator.mul, xrange(1, n + 1))
120
>>>
使用 for 循环:
sum_ = 1
for i in range(1, 6):
sum_ *= i
print sum_
或者,您可以使用从 while 循环中返回值的 yield关键字。例如:
def yeild_example():
current_answer = 1
for i in range(1,n+1):
current_answer *= i
yield current_answer
它将懒惰地为您评估答案。如果您只想要一切,这可能是要走的路,但是如果您知道要存储东西,那么您可能应该像在其他答案中一样使用 return ,但这对于许多其他应用程序来说很好。
这被称为 a generator function,其背后的想法是它是一个在被询问时会“生成”答案的函数。与一次生成所有内容的标准函数相比,这允许您仅在需要时执行计算,并且通常会提高内存效率,尽管最好根据具体情况评估性能。一如既往。
**编辑:所以这不是 OP 提出的问题,但我认为这将是对 python 的一些非常简洁和灵活的东西的一个很好的介绍。
如果您更喜欢保留您的 while 循环结构,您可以这样做(有 1000 +1 种方法可以做到...):
x=1
result = 1
while x <= n:
x += 1
result *= x
将在哪里result存储阶乘。然后你可以 justreturn或printout result,或任何你想用它做的事情。
要访问循环中完成的计算,您必须使用计数器(具有有用且易于理解的名称),您将在其中存储计算结果。计算后,您只需返回或使用计数器作为循环的乘积。
sum_counter=0
x=0
while x < 10:
sum_counter +=x
x+=1
print sum_counter