查找Python中{for}循环生成的值的总和

时间:2018-06-15 13:38:35

标签: python for-loop

嗨,全新的,并且可能会遇到一个简单的问题 我有一个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

2 个答案:

答案 0 :(得分:3)

如果您想跟踪中间值:

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.S。您不需要定义和增加p - 您可以使用您的(当前未使用的)变量i - 由range自动递增。

答案 1 :(得分:-2)

你想要这个吗?

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