Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"bool is not subscriptable" error when not indexing into a bool - Python

Tags:

python

boolean

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?

like image 519
Kai036 Avatar asked Dec 06 '25 19:12

Kai036


2 Answers

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
like image 161
perennial_noob Avatar answered Dec 09 '25 09:12

perennial_noob


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.

like image 36
U12-Forward Avatar answered Dec 09 '25 10:12

U12-Forward