这个问题出现在我的期中,我意识到我做得不对,所以我想知道我哪里做错了。
我正在尝试定义一个函数count_char(string,char)
,该函数通过使用递归返回char处于问候状态的总次数。
def count_char(string,char):
#base case:
if len(string) < 1:
return
#recursive case:
if string[-1] == char:
total = count_char(string[0:len(string)-1],char) + 1
return total
运行count_char("hello","h")
时出现错误:
UnboundLocalError:分配前已引用局部变量“总计”
我不确定我还会怎么做,以便总数不是局部变量。