as a foreword: a lot of answers received meaningful edits in the meantime I was writing this answer. Don't hold it against me.
I'm throwing my two cents in here just because there's a lot of over-complicated answers.
This is a corrected copy-paste of the OP's effort.
def recursive_me(mystring, total=0):
chars = len(mystring)
if chars is 0:
print("Done")
return total
else:
first = int(mystring[0])
total += first
print(total)
recursive_me(mystring[1:], total)
first what happens is that we check the base case, if there's no left chars in the string. If the string length is 0 we return the total calculated ammount.
Otherwise, we turn the first of the chars into an int, and add it to total. The first error you have is that you wrote str[0]
. str
is a python built in type and the produced error would be something like "str is not subscriptable".
This error means that the str
can't be operated on by "[]" operator. The same would happen if you tried doing 1[0]
because 1
is a integer. The "[]" operator can only operate on lists, tuples and strings (I might've forgot some built-in type).
The second error you had was with the addition part. You had written total = + first
but the operator you are looking for is the +=
which in fact is just a shortened way to write a = a+b
.
Additionally, your original question was concerning about "python" forgetting the value of "total". This is because you have to either pass that value forward, or write your recursive function in a way that "forces" it to, what's called, evaluate your next call to your function on the spot.
In my example I'm sending the next call of the function recursive_me, the current total value. In the example given by @uselpa; above he's making python evaluate the next call to the function by putting it after operator +
:
return int(mystring[0]) + recursive_me(mystring[1:])
this then gets to be (for recursive_me("4567")
)
return int(4)+recursive_me("567")
return int(4)+int(5)+recursive_me("67")
....
return int(4)+int(5)+int(6)+int(7)+0
because python needs to return a value here, but the expression keeps calling new functions and python can't return until it evaluates all of them to a final number (in this case at least).