0

For this code, I'm getting a not defined error which is:

  values = line.split(" ")  
NameError: name 'line' is not defined

I'm not sure why line is not defined. Someone help me please. This is probably something stupid and if it is because it needs to be something else, can someone tell me what that is please?

with open("Class1.csv") as f:
    columns = f.readline().strip().split(" ")
    numRows = 0
    sums = [1] * len(columns)

    for line in f:
    # Skip empty lines
        if not line.strip():
            continue

values = line.split(" ") # This seems to be the problematic line.
for i in range(1,len(values)):

     sums[i] += int(values[i])
     numRows += 1

for index, i in enumerate (sums):
    print (columns[index], 1.0 * (i) / (numRows))
Bakuriu
  • 98,325
  • 22
  • 197
  • 231

2 Answers2

1

Your for loop isn't looping at all, hence the line identifier isn't assigned and thus the error.

You probably have a one-line file which is completely consumed before the loop.

Note: in python for loops and with statements do not introduce a new scope! See:

In [1]: for x in range(5):
   ...:     print(x)
   ...:     
0
1
2
3
4

In [2]: x   # here I can still use x!
Out[2]: 4

so what you are doing is perfectly valid. The problem is that if the for doesn't perform an iteration you get a NameError:

In [1]: for x in []:
   ...:     print('no iteration performed')

In [2]: x
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-401b30e3b8b5> in <module>()
----> 1 x

NameError: name 'x' is not defined

Only function definition introduce a new scope.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
0
values = line.split(" ") 

is outside your for loop, so you definitely shouldn't write something like that.

However, syntactically, "line" would be defined in the global scope after the first loop iteration. In this instance the error is because your for loop doesn't iterate even once (because of your input). If it did, "line" would have the last value of the loop.

Example:

for a in range(2):
  pass
print (a)

will print 1

however:

for a in range(0):
  pass
print (a)

will return an error because a is never defined, range(0) having no elements.

NameError: name 'a' is not defined
GCord
  • 146
  • 6