Question :
Hello, I’m creating a character converter for your ascii code through a recursive function in Python. However I have an “int ‘object is not iterable” problem.
My code is this:
def cod(n):
for i in n:
i = str(i)
if len(n) == 1:
ascii = ord(i)
return ascii
else:
ascii = ord(i) + cod(ord(i))
return ascii
The error that returns is as follows:
Traceback (most recent call last):
File "python", line 1, in <module>
File "python", line 8, in codifica
File "python", line 2, in codifica
TypeError: 'int' object is not iterable
I’m basically using ord()
to get the ASCII character number. When I call only one character, everything works fine. If you try to spend more than one you start the problems.
The problem seems to be that the variable i
is being treated as integer but supposedly I convert to string when doing i = str(i)
What I want is that when executing the function cod('ola')
it returns 11110897
which corresponds to the conversion of each of the characters to ASCII.
Can anyone help me figure out where I’m failing?
Answer :
Your problem is here:
cod(ord(i))
You are calling the function cod
recursively passing the result of ord
– and therefore an integer – as argument. But since the first thing that cod
does is iterate over the argument:
for i in n: # n na segunda chamada é o resultado de ord(i)
Then he complains that he can not iterate over an integer.
Since you’re using for
, I imagine your intent was not to create a recursive code. In this case, create a string “result” and go throwing the values found in it, in order to return it (this even avoids this if
where you test if the string size is 1
or not):
def cod(n):
resultado = ""
for i in n:
# i já é uma string, não precisa fazer i = str(i)
ascii = ord(i)
resultado += str(ascii) # ascii é um número, então precisa fazer str(ascii)
return resultado
A recursive solution, on the other hand, would not require a for
. Just check if the string is empty or not, and if it is not, apply ord
to its first character and concatenate with the result of applying cod
to its suffix:
def cod(n):
return "" if n == "" else str(ord(n[0])) + cod(n[1:])