在Python中查找for循环生成的值之和

2024-04-20 05:59:51 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,全新的,正在努力解决一个可能的简单问题。
我有一个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

Tags: oftheto方法fornum例子total
2条回答

如果要跟踪中间值:

def nSum(num):
    #calculating values for the variable (num) to the p power:
    values = []
    for p in range(num):
        currentVal = num * 10**p
        #running total of the curent values:
        newValue = currentVal + (values[-1] if values else 0)
        values.append(newValue)

    return values

print(sum(nSum(3))) #Want nSum to be total of all the newValues from the loop

如果你不关心它们,你可以删除列表,只使用累加器:

def nSum(num):
    #calculating values for the variable (num) to the p power:
    total = 0
    new_value = 0
    for p in range(num):
        currentVal = num * 10**p
        #running total of the curent values:
        new_value += currentVal
        total += new_value

    return total

print(nSum(3))

另外,您不需要定义和增加p,只需使用您的(当前未使用的)变量i,它会自动增加range。你知道吗

你想要这个吗?你知道吗

def nSum(num):
    #calculating values for the variable (num) to the p power:
    p = 0
    newValue = 0 
    total_value=0 #new variable
    for i in range(num):
        currentVal = num * 10**p
        p = p+1
    #running total of the curent values:
        newValue = currentVal + newValue
        print(newValue)
        total_value+=newValue #new line
    return total_value

print(nSum(3)) #Want nSum to be total of all the newValues from the loop

或者不使用p也可以这样做变数。你呢只能使用i变化无常,就像地址:

def nSum(num):
    #calculating values for the variable (num) to the p power:
    newValue = 0
    total_value=0
    for i in range(num):
        currentVal = num * 10**i
    #running total of the curent values:
        newValue = currentVal + newValue
        print(newValue)
        total_value+=newValue
    return total_value

print(nSum(3)) #Want nSum to be total of all the newValues from the loop

相关问题 更多 >