Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error- local variable referenced before assignment

What I’m sure is another simple error, but I’m going around in circles. I’m trying to get it to show the first 10 lines in a csv using a function. I can get 1 line to show before it throws an error. Maybe my rows=0 needs to be moved down further, but I’m not sure and my attempts at moving it hasn’t worked?


rows = 0

def lines():
    with open('iamacsvfile.csv') as file:
        dictreader = csv.DictReader(file)
        for row in dictreader:
            print(row)
            rows=rows+1
            if(rows>=10):
                break

lines()

UnboundLocalError Traceback (most recent call last)
Input In [57], in <cell line: 14>()
11 if(rows>=5):
12 break
—> 14 lines()

Input In [57], in lines()
8 for row in dictreader:
9 print(row)
—> 10 rows=rows+1
11 if(rows>=5):
12 break

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

UnboundLocalError: local variable ‘rows’ referenced before assignment

>Solution :

This should work:

def lines():
    rows = 0
    with open('iamacsvfile.csv') as file:
        dictreader = csv.DictReader(file)
        for row in dictreader:
            print(row)
            rows=rows+1
            if(rows>=10):
                break

lines()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading