0

This question comes from meeting the code below and not making sense of exactly what happens: when ran in python 3 it produces an error that says the variable i is not defined. But when executed in python 2, it runs smoothly and even prints the value of i.

The relevant code is this:

n_chi = pdbstruct.get_n_chi(res)

print 'n_chi'
print n_chi


rot_vels = [get_rot_vel_chi(res, i) for i in range(n_chi)]

for i_chi in reversed(range(n_chi)):

  # if chi angle has exceeded bounds, change direction
  # else keep same direction

  chi = pdbstruct.calculate_chi(res, i_chi)

  print "Show i"
  print i

  delta_chi = vector3d.normalize_angle(chi - mean_chi_values[i])

,where I would like to draw attention and understand, how in python 2 this code can return:

n_chi                                                                 
2                                                                     
Show i
1

but, as I would expect, in python 3 it returns:

NameError: name 'i' is not defined

If there is something obvious in this that I fail to see, please let me know; but it seems strange to me at least that python 2 manages to run, somehow having a value for i.

Note also that the value of i doesn't change, nor the value of n_chi.


Small edit:

It really seems to me that since i is called inside the comprehension list and range is also called, the value i=1 comes from the last value of the iteration of range(n_chi).

So, in python 2, is i somehow defined globally?

  • @SergiyKolesnikov Perhaps, let me check it further. If it answers the post above, would it be best to remove mine or add a duplicate flag? Thanks. – Constantine Black Jan 06 '21 at 10:32
  • @SergiyKolesnikov It does. Thank you again for the reference. I will flag my own post as a duplicate, in case other users like me won't know how to exactly search for this behavior. – Constantine Black Jan 06 '21 at 10:36

0 Answers0