Sep-13-2018, 02:05 PM
(This post was last modified: Sep-13-2018, 09:46 PM by Drone4four.)
I’ve got a string: "Secret agents are super good at staying hidden."
I’m trying to use a for loop to print out only the words with an even number of characters.
In my code below, I’ve assigned the string to a variable. I’ve split each word up into items in a new list by using the split function. Then I’ve counted the length of each item and assigned it to a new variable called,
Instead I get this traceback:
Can someone better explain why my code is actually doing and how I can get the desired/expected output?
For my future reference, this forum thread refers to Task #2 in Jose Portilla’s so called 04-Field-Readiness-Exam-2 in his “Narrative Journey” Udemy Python course material (on GitHub: Pierian-Data/Python-Narrative-Journey).
I’m trying to use a for loop to print out only the words with an even number of characters.
In my code below, I’ve assigned the string to a variable. I’ve split each word up into items in a new list by using the split function. Then I’ve counted the length of each item and assigned it to a new variable called,
counted_string
. Then I iterate through each item. I take each item and apply a modulus of two. If the remainder is 0 (meaning the word has an even number of characters) only then that particular item is printed. This is what I am trying to do in following code snippet I’ve written:mystring = "Secret agents are super good at staying hidden." mystring.split() counted_string = len(mystring) int(counted_string) for i in counted_string: if i %2 == 0: print(i)I was expecting this output:
Quote:Secret
agents
good
at
Instead I get this traceback:
TypeError Traceback (most recent call last) <ipython-input-28-5b7261c4eed7> in <module>() 3 counted_string = len(mystring) 4 int(counted_string) ----> 5 for i in counted_string: 6 if i %2 == 0: 7 print(i) TypeError: 'int' object is not iterableI'm doing something wrong at line 5. The traceback is saying that my
counted_string
variable is not iterable (because it’s an integer?). Only strings and lists are iterable. So if I substitute counted_string
in my for loop with the original mystring
variable, I don’t get any output.Can someone better explain why my code is actually doing and how I can get the desired/expected output?
For my future reference, this forum thread refers to Task #2 in Jose Portilla’s so called 04-Field-Readiness-Exam-2 in his “Narrative Journey” Udemy Python course material (on GitHub: Pierian-Data/Python-Narrative-Journey).