The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams

--

Chapters
00:00 &Quot;Bool Is Not Subscriptable&Quot; Error When Not Indexing Into A Bool - Python
00:47 Answer 1 Score 0
01:11 Accepted Answer Score 2
01:42 Answer 3 Score 1
01:57 Thank you

--

Full question
https://stackoverflow.com/questions/5536...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #boolean

#avk47



ACCEPTED ANSWER

Score 2


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



ANSWER 2

Score 1


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.




ANSWER 3

Score 0


What did you init the var loop_started as? (Or in another word, what value does loop_started have when the function have not been executed?)

If loop_started is False before the function is executed, then the function would return False directly.

A quick fix would be adding an empty string after all boolean return statements.