3 回答

TA貢獻1847條經驗 獲得超7個贊
問題是,當到達像“+”或“-”這樣的字符時,您實際上是在返回布爾值,但if in_loop(i)[1] == 'loop starting':仍然在訪問。
您必須返回一致的返回類型才能使第二個 for 循環代碼工作。例如,查看下面對您的代碼的注釋:
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

TA貢獻1880條經驗 獲得超4個贊
這種情況只有當你輸入的東西是不是'['
還是']'
,因為它會到了第二if
的if loop_started:
,并且默認如果內部條件不及格,那就只是return True
,所以這就是為什么它不工作。

TA貢獻1794條經驗 獲得超7個贊
你將 var 初始化loop_started
為什么?(或者換句話說,loop_started
當函數沒有被執行時有什么價值?)
如果loop_started
是False
在函數執行之前,則函數將直接返回 False。
一個快速的解決方法是在所有布爾返回語句之后添加一個空字符串。
添加回答
舉報