Skip to main content
 首页 » 编程设计

python之查找从 Python 中的 for 循环生成的值的总和

2024年12月31日9Renyi-Fan

你好,全新的,正在为一个可能很简单的问题而苦苦挣扎。
我有一个 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 

请您参考如下方法:

如果您想跟踪中间值:

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.