【发布时间】:2019-11-12 11:22:18
【问题描述】:
这个问题出现在我的期中考试中,我意识到我没有做对,所以我想知道我哪里错了。
我正在尝试定义一个函数 count_char(string, char),它使用递归返回 char 在 hello 中的总次数。
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: 赋值前引用了局部变量 'total'
我不确定我还能怎么做,这样总就不是局部变量了。
【问题讨论】:
-
你在自己内部使用函数
count_char()。