Throw TypeError: 'int' object is not iterable in Python
Hello you guys, I am a newbie in Python and I'm also studying more about Python.
I have some lines of code I want to find text and count time it found. I code function as below:
def find_word(intput, textsearch):
found = 0
for i in len(intput):
if intput[i] == textsearch:
found = found + 1
return found
intcount = find_word("I'm learning python" , "n")
print(intcount)
But I get an exception throw TypeError: 'int' object is not iterable when I run code above.
Traceback (most recent call last):
File "main.py", line 8, in <module>
intcount = find_word("I'm learning python" , "n")
File "main.py", line 3, in find_word
for i in len(intput):
TypeError: 'int' object is not iterable
And I am using python 3.8.2
Anyone can explain it to me? How can I solve it?
Thanks for any suggestions.
-
M0
Mobile Legend Oct 07 2021
You can try run command
print(len(intput))
You can see it print out 19 and it is a number and not is iterable.
So to fix this issue you can use
range
method to help interable withfor
loop. See code below (line 3):def find_word(intput, textsearch): found = 0 for i in range(len(intput)): if intput[i] == textsearch: found = found + 1 return found intcount = find_word("I'm learning python" , "n") print(intcount)
#Output is 3
I hope it helpful for you.
-
M0
Minh Phan Oct 07 2021
Change:
for i in len(intput):
to
for i in range(len(intput)):
And it will be solved for you.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.