嗨,全新的,正在努力解决一个可能的简单问题。
我有一个for循环,创建值并在生成时打印运行总数。
我需要找到一种方法来打印这些运行总数的总和(在下面的例子中:3+33+333),我感觉嵌套循环是一种选择,但不确定它会去哪里。我接近了吗?(谢谢)
以下是迄今为止我的代码:
def nSum(num):
#calculating values for the variable (num) to the p power:
p = 0
newValue = 0
for i in range(num):
currentVal = num * 10**p
p = p+1
#running total of the curent values:
newValue = currentVal + newValue
print(newValue)
return newValue
print(nSum(3)) #Want nSum to be total of all the newValues from the loop
如果要跟踪中间值:
如果你不关心它们,你可以删除列表,只使用累加器:
另外,您不需要定义和增加
p
,只需使用您的(当前未使用的)变量i
,它会自动增加range
。你知道吗你想要这个吗?你知道吗
或者不使用
p
也可以这样做变数。你呢只能使用i
变化无常,就像地址:相关问题 更多 >
编程相关推荐