1

I am relatively new to programming and I am suffering from what appears to be a simple problem.

Here's the snippet that is causing the problem (it is part of this larger function: http://pastebin.com/2apwWsEv):

for i in range(4,12):                       # remove nulls
    if not row[i]:
        row[i] = False
    if row[i] and (i % 2):                          # odd rows (time)
        print row[i]
        time = row[i].split(':')
        row[i] = int(time[0]) * 3600 + int(time[1]) * 60 + int(time[2])

Output:

row[i] = int(time[0]) * 3600 + int(time[1]) * 60 + int(time[2])
UnboundLocalError: local variable 'time' referenced before assignment

It seems I assigned time the value of row[i].split(':'), so I do not understand where the error is.

I tried changing around the second if statement (to a more conventional elif, etc) but that did not change the error.

(The time field, of the csv data, is in the format of hh:mm:ss and I am trying to convert it to seconds.)

Can someone please explain how time is being used before it is assigned?

BBedit
  • 7,037
  • 7
  • 37
  • 50

2 Answers2

4

In your pastebin, the line row[i] = int(... is indented using four spaces and four tabs. Even though the line appears to have the same indentation as the line prior to it, it's actually indented one less when interpreted by Python.

Don't intermix tabs and spaces; use only one or the other. The prevailing style is to use only spaces.

Kevin
  • 74,910
  • 12
  • 133
  • 166
1
  1. Please don't use a name of a libray for the name of a variable. 'time' is definitly a libray.
  2. If you want to use global variables in a function (and don't get the 'referenced before assignment'-error ;-) ) write

global name_of_variable

in your code at the beginning of the function (see Using global variables in a function other than the one that created them)

Community
  • 1
  • 1
palsch
  • 5,528
  • 4
  • 21
  • 32