Medallyon
Medallyon

Reputation: 120

Python - variable in a for loop acts as if it didn't exist

In the all-around context, I have a .csv file which I am reading data from and then I want to know how many rows there are in the file.

I've attempted doing that with this code:

for row in CharsDict:
    IDsQuant = sum(1 for row in CharsDict)
IDsQuant = int(IDsQuant)

But whenever I try to do something with the variable IDsQuant (like the above IDsQuant = int(IDsQuant)), it gives me this error:

UnboundLocalError: local variable 'IDsQuant' referenced before assignment

How can I solve this problem?

Thanks in advance.

Upvotes: 0

Views: 183

Answers (3)

Medallyon
Medallyon

Reputation: 120

It seems that this

for row in CharsDict:
    IDsQuant += 1
IDsQuant = int(IDsQuant)

is somewhat more effective and useful than

for row in CharsDict:
    IDsQuant = sum(1 for row in CharsDict)
IDsQuant = int(IDsQuant)

I seem to get no more errors by using this alternative. Thanks for the help!

Upvotes: 0

Rafael Lerm
Rafael Lerm

Reputation: 1400

You are right in assuming that your code should work, as loops don't create a new scope in Python.

However, if the body of the loop is not executed for some reason (such as CharsDict being an empty container), the IDsQuant variable will not have been created, generating the error you have seen.

The code below shows an example of this happening --- same code, running with different arguments. In the second call of the example function, the loop will not run, reproducing the situation you have, with the same error.

def test_scope(n_loops):                                                     
    for i in range(n_loops):                                                    
        variable = i                                                         
    return variable                                                          


if __name__ == '__main__':                                                   
    print('First test:', test_scope(1))                                      

    print('Empty loop:', test_scope(0))   

Upvotes: 2

Fred Mitchell
Fred Mitchell

Reputation: 2161

You have not defined what CharsDict is in your example, nor how you are reading the file.

If your "read" returns an array - rows, then just the number of rows will be len (rows).

If OTOH, you are iterating through an iterable, you can increment a count that was set to zero before the iteration starts.

Upvotes: 0

Related Questions