0

When looping through the contents of a CSV file I am trying to create a start time and an end time;

I know the forms submitted based on the row['form'] and I log the time of submitting for those forms, I am trying to create a start and end time so I can later get an average time for the completion of their forms.

for row in rows:
    branch = Branch(row['user_id'], row['form'], row['time'])
    if branch.id == row['user_id']:
        if branch.form == 'signup':
            time = {i: {'start': branch.time}}
            print(time)
        elif branch.form == 'submit':
            time = {i: {'end': branch.time}}
            print(time)

        print(time) # line 27

The problem with the code snippet above is that for the print() inside of the conditional statements it works just fine; I get the start time as well as the end time.

But when I try to print it outside of the conditional statement it does not work:

Traceback (most recent call last):
  File "index.py", line 27, in <module>
    print(time)
NameError: name 'time' is not defined

Now, if I print time outside of the for loop then it gives me the last value; I cannot get any of the previous values.

Sam
  • 2,856
  • 3
  • 18
  • 29
  • 2
    What is the value of `branch.form`? Are you sure that it is `signup` or `submit`? – Jim Wright Mar 01 '18 at 03:32
  • @JimWright it is the name of the form in a `str`. Yes, `signup` and `submit` are there among the others. – Sam Mar 01 '18 at 03:34
  • 5
    My point was if it is anything but `signup` and `submit`, then your are not defining `time`. – Jim Wright Mar 01 '18 at 03:34
  • @JimWright So it doesn't increment to the dictionary `time` (e.g. `time[i]`)? How would I assign the values then. There are 5 forms, I just need the first and last times. – Sam Mar 01 '18 at 03:36
  • Likely, `branch.form` is neither `'signup'` nor `'submit'`. Certainly, `if` and `else` blocks do not have their own scope. – juanpa.arrivillaga Mar 01 '18 at 03:38
  • 1
    I agree. Add an `else` at least to define `time` if you are using it for all values of `branch.form` – rishijd Mar 01 '18 at 03:43
  • So simply add a `else` statemt at the end? – Sam Mar 01 '18 at 03:44
  • Yes, add an else statement and set a default time. Maybe `None` would be good for this case? – Jim Wright Mar 01 '18 at 04:19
  • If `branch.form` is not equal to `'signup'`, and is also not equal to `'submit'`, **what should the value of `time` be**? In fact, **should the `print` happen**? Nobody else can answer these questions for you. – Karl Knechtel Sep 12 '22 at 11:11

1 Answers1

0

If you want the "time" variable redefinable and accessible in multiple scopes, you'll need to use the global key word. See my answer here.

Hope it helps.

Stephen Collins
  • 845
  • 7
  • 12