Spell Elements Recursive

I have been trying to make a recursive function, which has two parameters, a word and a list, the list is the symbols of the elements as they are: H for Hydrogen, K for potassium, this is an example of what my program should return : The word Silver can be spelled as SiLvEr.

My function has some errors that I don't have clear how to correct them, I show you my function

def spell_elements(palabra:str , lista:list):
    
    if palabra == "":
        return 
    
    if palabra[0] in lista:
        return palabra[0] + spell_elements(palabra.strip(palabra[0]), lista)
    
    elif palabra[:2] in lista:
        return palabra[:2] + spell_elements(palabra.strip(palabra[:2]), lista)
    
    elif palabra[:3] in lista:
        return palabra[:3] + spell_elements(palabra.strip(palabra[:3]), lista)

# Example
print(spell_elements("silver", elementos)
# output -> SiLvEr

The program gives me the error "TypeError: can only concatenate str (not "NoneType") to str". I did the debug of the function and it does it correctly but if it does not enter in any condition of the if's and elif's it gives the same problem when it enters in a good way and the word runs out of characters.


The problem is in two places:

  1. Just a raw return returns a value of None. So when you call spell_elements() recursively and try to concatenate a string, you get an error. You probably can fix this by doing return "".

  2. You have if with several elif but no else. If none of the conditions are met, the function terminates when it reaches the end and returns None by default. Again, you can fix this by adding return "" at the end of the function.