Should you declare variable before hand in python when using list append and For loop?

Viewed 1061

After receiving an error in the code below i ended up adding

    new_list = [] 
    summation = 0

after the second line. But i fail to understand why i had to do that. I thought variables did not have to be declared early on in python

    a = int(input())
    b = int(input())
    while a <= b:
    if a % 3 == 0:
        new_list.append(a)
        a += 1
    for number in new_list:
        summation += int(number)
    print(summation / len(new_list))
2 Answers

In general, Python does not require variables to be declared (except for a couple of cases). In this case, you are not declaring a variable but rather initializing it. Let's imagine that variables are boxes. In python, you don't have to say, please make a box and call it x. The issue is when you come across summation += int(number). This tells python, please take out whatever is in the box called summation, add int(number) to it, and put it back in the box. But you haven't yet put anything in the box. So python says sorry, there's nothing in the box at the moment so I can't take anything out. Same for new_list.append(a), that asks python to please append a to whatever is in the box. So python looks in the box to figure out how to append something to it but it can't find anything so it shows an error.

You may ask, why doesn’t python just put 0 in the box? Well, python doesn't know that what you want in the box is an int. Maybe you wanted a fraction, a complex number, or something you make up yourself that happens to be able to be added to a number. The same goes for the list, python does not know that you wanted a list and not a set, dictionary, tuple, counter, queue, or some other collection. So rather than guess, and possibly get it wrong (which would cause all kinds of weird bugs due to the slight differences in how these work with addition), it just gives you an error.

It depends on what you're doing with the variable. If you're assigning a value to the variable, it will initialize the variable in the loop itself. But if you want to modify a variable like you did with .append(), you have to declare it first as it has to be declared to be modified.

Related