x = int(input()) l = for i in range(x): l.append(input().split(" ")) for i in range(x): k = int(l[i]) sum = int(l[i]) odd = for j in range(int(l[i])): odd.append(1+2*j) for j in range(len(odd)): s =0 for l in range(len(odd)): if(odd[j]==odd[l]): s = s+ odd[l]*k else: s = s+ odd[l] if(s==sum): print(odd[j]) break
When I run this code, it works perfectly fine for 1 iteration. But as soon as we move to next iteration, the code starts showing error:
TypeError: ‘int’ object is not subscriptable
in the line where I have declared
k = l[i]. What’s causing this error and how can I solve it?
for l in range(len(odd)):
l. Loops (and all other control structures for that matter) don’t introduce a new scope in Python, so that
l is the exact same variable as the
l you defined at the start. When
k = l[i] is reached on the next iteration, you’re attempting to index an
int, hence the error.
You’ll need to pick a different name for the variable in the for loop.