Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialPhillip Bailey
1,822 PointsPrinting odd values. Close but not really.
This is what I have so far, but I understand i'm not using slices. I feel like maybe I'm making this harder than it should be. I thought it would be cool to iterate through and return od indexes by comparing the current index being divisible by 2 or not. I was getting erros about not all things were converted etc. And, since if I use a string, I cant do math on a sting I think, thats why I should retry this with slices only. Any advice would be helpful just to see how I could use this for loop in a similar approach.
def odds(word): for odd in word: if (odd % 2) >0: print(odd) return(odd)
list_1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] odds(list_1)
def first_4(iterable):
return iterable[0:4]
def first_and_last_4(iterable):
#first_4 = iterable[0:4]
return iterable[0:4] + iterable[-4:]
def odds(word):
for odd in word:
if (odd % 2) >0:
print(odd)
return(odd)
list_1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
odds(list_1)
1 Answer
Steven Parker
231,269 PointsYour idea is sound, but needs a bit more work. Doing this with slices is a whole lot easier, and is the point of this challenge. You should really try to do it with a slice.
But just so you'll know what went wrong:
- you need to test the index, not the item itself
- you'd probably need the "enumerate" function to get the indexes with the items
- you need to return a new list containing all the odd-indexed items (not just one of them)
- you don't need to "print" anything
Phillip Bailey
1,822 PointsPhillip Bailey
1,822 PointsOkay, I have not seen the enumerate function yet. I tried this and it work in IDLE but still wrong answer with slices. def
odds(the_iterable): return the_iterable[::2] when I put a list through it, seems to work and if I put a string it works but im still a little lost.
Steven Parker
231,269 PointsSteven Parker
231,269 PointsYou're really close, the step of 2 was a good idea. But the index numbers start with 0, which means you would be returning the evens instead of the odds. So give your slice a start value so you get the odds instead.