Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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))
like image 528
user14617117 Avatar asked May 26 '26 01:05

user14617117


1 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.

like image 183
Bryce Avatar answered May 27 '26 14:05

Bryce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!