Cade
Cade

Reputation: 39

My variables change inside or outside of a loop

I am trying to write a program that adds numbers in a list ( list[1,2,3] should return 1+2+3 = 6.

This one doesn't work:

def sum_list (list): 
    for number in list:
        old_value=0
        new_value=old_value+number
        old_value=new_value
    return new_value

This one does work:

def sum_list (list):
    old_value=0
    for number in list:        
        new_value=old_value+number
        old_value=new_value
    return new_value

Can anyone explain why the program doesn't work in old_value is within the loop?

Upvotes: 2

Views: 52

Answers (2)

UglyCode
UglyCode

Reputation: 315

You code is logically wrong. You are re initializing the value of old_value to 0 every time the loop runs.

First method only retains the last entry in the list because old_value is always 0.

Upvotes: 1

gefei
gefei

Reputation: 19766

In the first piece of code, old_value is set to 0 in every iteration. therefore, the last line in the loop, old_value=new_value, does not change anything

Upvotes: 1

Related Questions