I have the following function:
def in_loop(i):
global loop_started
if i == '[':
loop_started = True
return [True, 'loop starting']
if loop_started:
if i == ']':
loop_started = False
return [True, 'loop over']
return True
return False
I believe this is returning a tuple that looks like (True, 'loop over') when i is "]". I then try to index into it with
for index, i in enumerate(code):
if in_loop(i):
loop_counter += 1
if in_loop(i)[1] == 'loop starting':
loop_start = index
if in_loop(i)[1] == 'loop over':
loops[f'loop{loop_num}'] = {'start': loop_start, 'end': index}
loop_num += 1
but this raises an error
TypeError: 'bool' object is not subscriptable
Also, code = "+++++[-][-]".
Why is this error being raised when I'm indexing into a tuple?
The problem is that when the characters like '+' or '-' are reached you are essentially returning boolean but are accessing if in_loop(i)[1] == 'loop starting': nonetheless.
You must return a consistent return type for the 2nd for-loop code to work. For ex, look at the comments below to your code:
def in_loop(i):
global loop_started
if i == '[':
loop_started = True
return [True, 'loop starting']
if loop_started:
if i == ']':
loop_started = False
return [True, 'loop over']
return True #This will have side effects and is inconsistent with your other returns of in_loop
return False #This will have side effects and is inconsistent with your other returns of in_loop
This is the case only when you input something that isn't '[' or ']', because it would got to the second if of if loop_started:, and default if the inner condition doesn't pass, it would just return True, so that is why it doesn't work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With